0% found this document useful (0 votes)
5 views3 pages

Simple Sorting Algorithms Explained

This document discusses three sorting algorithms: bubble sort, selection sort, and insertion sort. It provides code examples to implement each algorithm and sort an array of integers. For each algorithm, it loops through the array to sort it and outputs the sorted array.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views3 pages

Simple Sorting Algorithms Explained

This document discusses three sorting algorithms: bubble sort, selection sort, and insertion sort. It provides code examples to implement each algorithm and sort an array of integers. For each algorithm, it loops through the array to sort it and outputs the sorted array.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Implementing simple sorting algorithms

1. Bubble Sort Algorithm.

#include<iostream>
using namespace std;
int main ()
{
int i, j,temp,pass=0;
int a[10] = {10,2,0,14,43,25,18,1,5,45};
cout <<"Input list ...\n";
for(i = 0; i<10; i++) {
cout <<a[i]<<"\t";
}
cout<<endl;
for(i = 0; i<10; i++) {
for(j = i+1; j<10; j++)
{
if(a[j] < a[i]) {
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
pass++;
}
cout <<"Sorted Element List ...\n";
for(i = 0; i<10; i++) {
cout <<a[i]<<"\t";
}
cout<<"\nNumber of passes taken to sort the list:"<<pass<<endl;
return 0;
}

2. Selection Sort algorithm.


#include<iostream>
using namespace std;
int findSmallest (int[],int);
int main ()
{
int myarray[10] = {11,5,2,20,42,53,23,34,101,22};
int pos,temp,pass=0;
cout<<"\n Input list of elements to be Sorted\n";
for(int i=0;i<10;i++)
{
cout<<myarray[i]<<"\t";
}
for(int i=0;i<10;i++)
{
pos = findSmallest (myarray,i);
temp = myarray[i];
myarray[i]=myarray[pos];
myarray[pos] = temp;
pass++;
}
cout<<"\n Sorted list of elements is\n";
for(int i=0;i<10;i++)
{
cout<<myarray[i]<<"\t";
}
cout<<"\nNumber of passes required to sort the array: "<<pass;
return 0;
}
int findSmallest(int myarray[],int i)
{
int ele_small,position,j;
ele_small = myarray[i];
position = i;
for(j=i+1;j<10;j++)
{
if(myarray[j]<ele_small)
{
ele_small = myarray[j];
position=j;
}
}
return position;
}

3. Insertion Sort Algorithm


#include<iostream>
using namespace std;
int main ()
{
int myarray[10] = { 12,4,3,1,15,45,33,21,10,2};

cout<<"\nInput list is \n";


for(int i=0;i<10;i++)
{
cout <<myarray[i]<<"\t";
}
for(int k=1; k<10; k++)
{
int temp = myarray[k];
int j= k-1;
while(j>=0 && temp <= myarray[j])
{
myarray[j+1] = myarray[j];
j = j-1;
}
myarray[j+1] = temp;
}
cout<<"\nSorted list is \n";
for(int i=0;i<10;i++)
{
cout <<myarray[i]<<"\t";
}
}

Common questions

Powered by AI

The modular design employing the `findSmallest` function enhances the readability and maintainability of the selection sort algorithm by breaking down the problem into smaller, understandable components. This function separates the logic to find the smallest element from the main sorting logic, creating clearer separation of concerns. Such modular design facilitates easier debugging, as each function can be tested and verified independently. Moreover, it provides a reusable function that could be independently called if needed elsewhere in the code. Modular code is often more maintainable as it allows for enhanced focus on specific sections, easier updates, and potential reuse .

Insertion Sort might be preferable for small datasets or real-time systems where quick execution with low overhead is crucial. Its O(n) performance on nearly sorted data, combined with its straightforward implementation and stable sorting feature, enables minimal processing time without complex management, which could introduce unnecessary complexity and latency in scenarios where simplicity and predictability are prioritized over raw computing speed .

The `findSmallest` method in the Selection Sort algorithm is responsible for identifying the smallest element from a specified starting index to the end of the list. It iterates through the unsorted portion of the list and keeps track of the smallest element's position. This method allows the main Selection Sort function to systematically swap the smallest discovered element with the first element in the unsorted region, progressively building a sorted portion of the list. By abstracting this functionality into a separate method, the implementation becomes more modular and easier to understand .

The inner 'while' loop in the Insertion Sort algorithm checks the condition `j>=0 && temp <= myarray[j]`. This condition ensures that elements are shifted to the right until the proper position for the current element, stored in `temp`, is found. The loop exits either when it reaches the start of the list (`j>=0` fails) or when a preceding element stays in its correct, sorted position (`temp <= myarray[j]` fails). Exiting at the correct moment ensures that the current element is inserted in the correct position to maintain an incremental build-up of a list sorted up to that point .

The main advantage of Insertion Sort is its efficiency when dealing with small or partially sorted arrays, offering a time complexity of O(n) in the best-case scenario when the array is nearly sorted. Unlike Bubble Sort and Selection Sort, Insertion Sort can take advantage of the existing order within a data structure, moving less often. This property also makes it a stable sorting algorithm, ensuring that equal elements maintain their relative order .

Selection Sort is an unstable sorting algorithm, meaning that it does not preserve the relative order of equal elements. If the data set contains multiple identical values, their original sequence could be altered upon sorting. This effect can be problematic when sorting records with primary and secondary keys, such as spreadsheet data where the Rows need to maintain relative positions based on secondary criteria. Unstable sorting algorithms like Selection Sort can disrupt analytics or sorting tasks where the original order provides significant context or meaning .

Bubble Sort, Selection Sort, and Insertion Sort all have a space complexity of O(1) as they require only a constant amount of additional space for swapping elements. This efficiency in space usage makes them suitable for sorting large datasets where memory is constrained, as they don't require additional data structures beyond the input array. While their time complexities differ, leading to different practical applications based on speed, their equal space complexity significance becomes a critical factor when operating where space is a limiting resource .

Insertion Sort is often preferred for small data sets because it runs efficiently in O(n) time on nearly sorted data, which optimizes its performance due to minimal shifts or swaps required. For completely randomized data of larger sizes, its O(n^2) performance still becomes a disadvantage compared to more advanced algorithms like Quick Sort or Merge Sort. However, for small data sets, the overhead incurred by more complex algorithms may outweigh their benefits, making Insertion Sort an ideal candidate, particularly in scenarios where the initialization overhead of other algorithms is not justified by the marginally improved speed on small arrays .

Bubble Sort repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order. This process continues until the entire list is sorted, which means it can take multiple passes through the entire list to sort it completely. It is not very efficient on large lists and performs poorly (O(n^2) time complexity) relative to other algorithms. Selection Sort, on the other hand, divides the input list into a sorted and an unsorted region. It repeatedly selects the smallest element from the unsorted region and moves it to the end of the sorted region, which also results in O(n^2) time complexity. However, Selection Sort generally makes fewer swaps compared to Bubble Sort, as it only swaps once per element placed in the sorted region .

The number of passes in sorting algorithms indicates how many times the algorithm goes through the list to achieve a sorted order. It is directly related to the algorithm's efficiency. For Bubble Sort, each pass ensures that at least one more element is placed in its correct position. However, in the worst-case scenario, Bubble Sort requires n-1 passes for a list of size n, which highlights its inefficiency for larger lists as the number of passes increases with the size of the input list. This inefficiency is reflected in its O(n^2) time complexity, where more passes imply more comparisons and potential swaps, increasing the overall execution time .

You might also like