sort algorithm
1. Bubble Sort
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in wrong order.
Example: First Pass: (514 2 8 ) –> (154 2 8 ), Here, algorithm compares the first two elements, and swaps since 5 > 1. ( 1542 8 ) –> ( 1452 8 ), Swap since 5 > 4 ( 1 4528 ) –> ( 1 4258 ), Swap since 5 > 2 ( 1 4 258) –> ( 1 4 258), Now, since these elements are already in order (8 > 5), algorithm does not swap them.
Second Pass: (142 5 8 ) –> (142 5 8 ) ( 1425 8 ) –> ( 1245 8 ), Swap since 4 > 2 ( 1 2458 ) –> ( 1 2458 ) ( 1 2 458) –> ( 1 2 458) Now, the array is already sorted, but our algorithm does not know if it is completed. The algorithm needs onewholepass withoutanyswap to know it is sorted.
Third Pass: (124 5 8 ) –> (124 5 8 ) ( 1245 8 ) –> ( 1245 8 ) ( 1 2458 ) –> ( 1 2458 ) ( 1 2 458) –> ( 1 2 458)
2. Merge Sort
3. QuickSort
4. Bucket Sort
The idea is to use bucket sort. Following is bucket algorithm.
5. Heap Sort
6. Cocktail Sort
two way bubble sort
The first stage loops through the array from left to right, just like the Bubble Sort. During the loop, adjacent items are compared and if value on the left is greater than the value on the right, then values are swapped. At the end of first iteration, largest number will reside at the end of the array.
The second stage loops through the array in opposite direction- starting from the item just before the most recently sorted item, and moving back to the start of the array. Here also, adjacent items are compared and are swapped if required.
7. Insertion Sort
Insertion sort is a simple sorting algorithm that works the way we sort playing cards in our hands.
Algorithm
// Sort an arr[] of size n
insertionSort(arr, n)
Loop from i = 1 to n-1.
……a) Pick element arr[i] and insert it into sorted sequence arr[0…i-1]
Uses:
Insertion sort is used when number of elements is small. It can also be useful when input array is almost sorted, only few elements are misplaced in complete big array.
Last updated
Was this helpful?