sorting algorithms in java
DESCRIPTION
asdasdTRANSCRIPT
Sorting Algorithms in Sorting Algorithms in JavaJava
Types of SortingTypes of Sorting BubbleSortBubbleSort HeapSortHeapSort InsertionSortInsertionSort QuickSortQuickSort SelectionSortSelectionSort ShellSortShellSort Bidirectional Bubble Bidirectional Bubble
Sort Sort Extra Storage Extra Storage
MergesortMergesort Radix SortRadix Sort BogoSortBogoSort
IntroSortIntroSort Binary Tree SortBinary Tree Sort Patience SortPatience Sort Counting SortCounting Sort Bucket SortBucket Sort Odd-Even Odd-Even
Transposition SortTransposition Sort Gnome SortGnome Sort Bozo SortBozo Sort Stooge SortStooge Sort Several Unique SortSeveral Unique Sort
BubbleSortBubbleSort
Bubble sort is a simple and well-known Bubble sort is a simple and well-known sorting algorithm. It is used in practice sorting algorithm. It is used in practice once in a blue moon and its main once in a blue moon and its main application is to make an introduction application is to make an introduction to the sorting algorithms. Bubble sort to the sorting algorithms. Bubble sort belongs to O(n2) sorting algorithms, belongs to O(n2) sorting algorithms, which makes it quite inefficient for which makes it quite inefficient for sorting large data volumes. Bubble sorting large data volumes. Bubble sort is sort is stablestable and and adaptiveadaptive. .
AlgorithmAlgorithm
Compare each pair of adjacent elements Compare each pair of adjacent elements from the beginning of an array and, if they from the beginning of an array and, if they are in reversed order, swap them.are in reversed order, swap them.
If at least one swap has been done, repeat If at least one swap has been done, repeat step 1.step 1.
You can imagine that on every step big You can imagine that on every step big bubbles float to the surface and stay bubbles float to the surface and stay there. At the step, when no bubble moves, there. At the step, when no bubble moves, sorting stops. Let us see an example of sorting stops. Let us see an example of sorting an array to make the idea of sorting an array to make the idea of bubble sort clearer.bubble sort clearer.
Example. Example. Sort {5, 1, 12, -5, Sort {5, 1, 12, -5, 16} using bubble sort. 16} using bubble sort.
Complexity analysisComplexity analysis
Average and worst case complexity of Average and worst case complexity of bubble sort is O(n2). Also, it makes O(n2) bubble sort is O(n2). Also, it makes O(n2) swaps in the worst case. Bubble sort is swaps in the worst case. Bubble sort is adaptive. It means that for almost sorted adaptive. It means that for almost sorted array it gives O(n) estimation. Avoid array it gives O(n) estimation. Avoid implementations, which don't check if implementations, which don't check if the array is already sorted on every step the array is already sorted on every step (any swaps made). This check (any swaps made). This check is necessary, in order to preserve is necessary, in order to preserve adaptive property.adaptive property.
Turtles and rabbitsTurtles and rabbits
One more problem of bubble sort is One more problem of bubble sort is that its running time badly depends that its running time badly depends on the initial order of the elements. on the initial order of the elements. Big elements (rabbits) go up fast, Big elements (rabbits) go up fast, while small ones (turtles) go down while small ones (turtles) go down very slow.very slow.
Turtle example. Turtle example. Thought, array {2, 3, 4, 5, 1} is almost sorted, it takes Thought, array {2, 3, 4, 5, 1} is almost sorted, it takes
O(n2) iterations to sort an array. Element {1} is a turtle. O(n2) iterations to sort an array. Element {1} is a turtle.
Rabbit example. Rabbit example.
Array {6, 1, 2, 3, 4, 5} is almost sorted too, but it takes Array {6, 1, 2, 3, 4, 5} is almost sorted too, but it takes O(n) iterations to sort it. Element {6} is a rabbit. This O(n) iterations to sort it. Element {6} is a rabbit. This example demonstrates adaptive property of the bubble example demonstrates adaptive property of the bubble sort. sort.
Sample Program of Sample Program of BubbleSortBubbleSort
public class public class bubbleSort{bubbleSort{ public static void public static void main(String main(String a[]){a[]){ int int i;i; int int array[] = {12,9,4,99,120,1,array[] = {12,9,4,99,120,1,3,10};3,10}; System.out.println("Values Befo System.out.println("Values Before the sort:\n");re the sort:\n"); forfor(i = 0; i < array.length; i++)(i = 0; i < array.length; i++) System.out.print( array[i] System.out.print( array[i]+" ");+" "); System.out.println(); System.out.println(); bubble_srt(array, array.length); bubble_srt(array, array.length); System.out.print("Values after t System.out.print("Values after the sort:\n");he sort:\n"); forfor(i = 0; i <array.length; i++)(i = 0; i <array.length; i++) System.out.print(array[i] System.out.print(array[i]+" ");+" "); System.out.println(); System.out.println(); System.out.println("PAUSE"); System.out.println("PAUSE"); } }
public static void public static void bubble_srt( bubble_srt( int int a[a[], ], int int n ){n ){ int int i, j,t=0;i, j,t=0; forfor(i = 0; i < n; i++){(i = 0; i < n; i++){ forfor(j = 1; j < (n-i); j++){(j = 1; j < (n-i); j++){ ifif(a[j-1] > a[j]){(a[j-1] > a[j]){ t = a[j-1]; t = a[j-1]; a[j-1]=a[j]; a[j-1]=a[j]; a[j]=t; a[j]=t; } } } } } } } }} }
HeapSortHeapSort
Heapsort is one of the best general-Heapsort is one of the best general-purpose sorting algorithms, a purpose sorting algorithms, a comparison sort and part of comparison sort and part of the the selectionselection sort family. Although sort family. Although somewhat slower in practice on most somewhat slower in practice on most machines than a good implementation machines than a good implementation of quicksort, it has the advantages of of quicksort, it has the advantages of worst-case O(n log n) worst-case O(n log n) runtimeruntime and being and being an in-place algorithm. Heapsort is not a an in-place algorithm. Heapsort is not a stable sort .stable sort .
Example of HeapSortExample of HeapSort
a. b. c.
d. e.
Sample Program of Sample Program of HeapSortHeapSort
public class HeapSorter public class HeapSorter {{ private static int[] a;private static int[] a; private static int n;private static int n;
public static void sort(int[] a0)public static void sort(int[] a0) {{ a=a0;a=a0; n=a.length;n=a.length; heapsort();heapsort(); }}
private static void heapsort()private static void heapsort() {{ buildheap();buildheap(); while (n>1)while (n>1) {{ n--;n--; exchange (0, n);exchange (0, n); downheap (0);downheap (0); } } }}
private static void buildheap()private static void buildheap() {{ for (int v=n/2-1; v>=0; v--)for (int v=n/2-1; v>=0; v--) downheap (v);downheap (v); }}
private static void downheap(int v)private static void downheap(int v) {{ int w=2*v+1; // first descendant of vint w=2*v+1; // first descendant of v while (w<n)while (w<n) {{ if (w+1<n) // is there a second descendant?if (w+1<n) // is there a second descendant? if (a[w+1]>a[w]) w++;if (a[w+1]>a[w]) w++; // w is the descendant of v with maximum // w is the descendant of v with maximum
labellabel
if (a[v]>=a[w]) return; // v has heap propertyif (a[v]>=a[w]) return; // v has heap property // otherwise// otherwise exchange(v, w); // exchange labels of v and exchange(v, w); // exchange labels of v and
ww v=w; // continuev=w; // continue w=2*v+1;w=2*v+1; }} }}
private static void exchange(int i, int j)private static void exchange(int i, int j) {{ int t=a[i];int t=a[i]; a[i]=a[j];a[i]=a[j]; a[j]=t;a[j]=t; }}
} // end class HeapSorter} // end class HeapSorter
InsertionSortInsertionSort Insertion sorting algorithm is similar to bubble sort. Insertion sorting algorithm is similar to bubble sort.
But insertion sort is more efficient than bubble But insertion sort is more efficient than bubble sort because in insertion sort the elements sort because in insertion sort the elements comparisons are less as compare to bubble sort. In comparisons are less as compare to bubble sort. In insertion sorting algorithm compare the value insertion sorting algorithm compare the value until all the prior elements are lesser than until all the prior elements are lesser than compared value is not found. This mean that the compared value is not found. This mean that the all previous values are lesser than compared all previous values are lesser than compared value. This algorithm is more efficient than the value. This algorithm is more efficient than the bubble sort .Insertion sort is a good choice for bubble sort .Insertion sort is a good choice for small values and for nearly-sorted values. There small values and for nearly-sorted values. There are more efficient algorithms such as quick sort, are more efficient algorithms such as quick sort, heap sort, or merge sort for large values . heap sort, or merge sort for large values .
Code description:Code description:
In insertion sorting take the element In insertion sorting take the element form left assign value into a variable. form left assign value into a variable. Then compare the value with previous Then compare the value with previous values. Put value so that values must be values. Put value so that values must be lesser than the previous values. Then lesser than the previous values. Then assign next value to a variable and assign next value to a variable and follow the same steps relatively until the follow the same steps relatively until the comparison not reached to end of comparison not reached to end of array. array.
Working of insertion sorting: Working of insertion sorting:
Sample program in insertion Sample program in insertion sortsort
public class public class InsertionSort{InsertionSort{ public static void public static void main(String main(String a[]){a[]){ int int i;i; int int array[] = {12,9,4,99,120,1,array[] = {12,9,4,99,120,1,3,10};3,10}; System.out.println("\n\ System.out.println("\n\n RoseIndia\n\n");n RoseIndia\n\n"); System.out.println(" Selecti System.out.println(" Selection Sort\n\n"); on Sort\n\n"); System.out.println("Values Befo System.out.println("Values Before the sort:\n"); re the sort:\n"); forfor(i = 0; i < array.length; i++)(i = 0; i < array.length; i++) System.out.print( array[i]+" "); System.out.print( array[i]+" "); System.out.println(); System.out.println(); insertion_srt(array, array.length insertion_srt(array, array.length); ); System.out.print("Values after t System.out.print("Values after the sort:\n"); he sort:\n");
forfor(i = 0; i <array.length; i++)(i = 0; i <array.length; i++) System.out.print(array[i]+" "); System.out.print(array[i]+" "); System.out.println(); System.out.println(); System.out.println("PAUSE"); System.out.println("PAUSE"); } }
public static void public static void insertion_srt(insertion_srt(int int array[], array[], int int n){n){ for for ((int int i = 1; i < n; i++){i = 1; i < n; i++){ int int j = i;j = i; int int B = array[i];B = array[i]; while while ((j > 0) && (array[j-((j > 0) && (array[j-1] > B)){1] > B)){ array[j] = array[j-1]; array[j] = array[j-1]; j--; j--; } } array[j] = B; array[j] = B; } } } }} }
QuickSortQuickSort
Quick sort algorithm is developed by C. Quick sort algorithm is developed by C. A. R. Hoare. Quick sort is a comparison A. R. Hoare. Quick sort is a comparison sort. The working of quick sort sort. The working of quick sort algorithm is depending on a divide-and-algorithm is depending on a divide-and-conquer strategy. A divide and conquer conquer strategy. A divide and conquer strategy is dividing an array into two strategy is dividing an array into two sub-arrays. Quick sort is one of the sub-arrays. Quick sort is one of the fastest and simplest sorting algorithm. fastest and simplest sorting algorithm. The complexity of quick sort in the The complexity of quick sort in the average case is Θ(n log(n)) and in the average case is Θ(n log(n)) and in the worst case is Θ(n2). worst case is Θ(n2).
Code description:Code description:
In quick sort algorithm pick an element from In quick sort algorithm pick an element from array of elements. This element is called the array of elements. This element is called the pivot. Then compare the the values from left to pivot. Then compare the the values from left to right until a greater element is find then swap the right until a greater element is find then swap the values. Again start comparison from right with values. Again start comparison from right with pivot. When lesser element is find then swap the pivot. When lesser element is find then swap the values.Follow the same steps until all elements values.Follow the same steps until all elements which are less than the pivot come before the which are less than the pivot come before the pivot and all elements greater than the pivot pivot and all elements greater than the pivot come after it. After this partitioning, the pivot is in come after it. After this partitioning, the pivot is in its last position. This is called the partition its last position. This is called the partition operation. Recursively sort the sub-array of lesser operation. Recursively sort the sub-array of lesser elements and the sub-array of greater elements. elements and the sub-array of greater elements.
Working of quick Working of quick sort algorithm:sort algorithm:
Input:12 9 4 99 120 1 3 10 13
Output:1 3 4 10 12 13 99 120
Sample program in quick Sample program in quick sortsort
public class public class QuickSort{QuickSort{ public static void public static void main(String a[]main(String a[]){){ int int i;i; int int array[] = {12,9,4,99,120,1,3,array[] = {12,9,4,99,120,1,3,10,13};10,13};
System.out.println("\n\ System.out.println("\n\n RoseIndia\n\n");n RoseIndia\n\n"); System.out.println(" Quick Sor System.out.println(" Quick Sort\n\n");t\n\n"); System.out.println("Values Before System.out.println("Values Before the sort:\n"); the sort:\n"); forfor(i = 0; i < array.length; i++)(i = 0; i < array.length; i++) System.out.print( array[i]+" "); System.out.print( array[i]+" "); System.out.println(); System.out.println(); quick_srt(array,0,array.length-1); quick_srt(array,0,array.length-1); System.out.print("Values after the System.out.print("Values after the sort:\n"); sort:\n"); forfor(i = 0; i <array.length; i++)(i = 0; i <array.length; i++) System.out.print(array[i]+" "); System.out.print(array[i]+" "); System.out.println(); System.out.println(); System.out.println("PAUSE"); System.out.println("PAUSE"); } }
public static void public static void quick_srt(quick_srt(int int array[],inarray[],int low, t low, int int n){n){ int int lo = low;lo = low; int int hi = n;hi = n; if if (lo >= n) {(lo >= n) { returnreturn;; } } int int mid = array[(lo + hi) / 2];mid = array[(lo + hi) / 2]; while while (lo < hi) {(lo < hi) { while while (lo<hi && array[lo] < mid) {(lo<hi && array[lo] < mid) { lo++; lo++; } } while while (lo<hi && array[hi] > mid) {(lo<hi && array[hi] > mid) { hi--; hi--; } } if if (lo < hi) {(lo < hi) { int int T = array[lo];T = array[lo]; array[lo] = array[hi]; array[lo] = array[hi]; array[hi] = T; array[hi] = T; } } } } if if (hi < lo) {(hi < lo) { int int T = hi;T = hi; hi = lo; hi = lo; lo = T; lo = T; } } quick_srt(array, low, lo); quick_srt(array, low, lo); quick_srt(array, lo == low ? lo+1 : lo, n) quick_srt(array, lo == low ? lo+1 : lo, n);; } }} }
SelectionSortSelectionSort In selection sorting algorithm, find the minimum In selection sorting algorithm, find the minimum
value in the array then swap it first position. In value in the array then swap it first position. In next step leave the first value and find the next step leave the first value and find the minimum value within remaining values. Then minimum value within remaining values. Then swap it with the value of minimum index position. swap it with the value of minimum index position. Sort the remaining values by using same steps. Sort the remaining values by using same steps. Selection sort is probably the most intuitive Selection sort is probably the most intuitive sorting algorithm to invent. sorting algorithm to invent.
The complexity of selection sort algorithm is in The complexity of selection sort algorithm is in worst-case, average-case, and best-case run-time worst-case, average-case, and best-case run-time of Θ(n2), assuming that of Θ(n2), assuming that comparisonscomparisons can be done can be done in constant time. in constant time.
Code description:Code description:
In selection sort algorithm to find the In selection sort algorithm to find the minimum value in the array. First assign minimum value in the array. First assign minimum index in key (index_of_min=x). minimum index in key (index_of_min=x). Then find the minimum value and assign Then find the minimum value and assign the index of minimum value in key the index of minimum value in key (index_of_min=y). Then swap the minimum (index_of_min=y). Then swap the minimum value with the value of minimum index. value with the value of minimum index. At next iteration leave the value of At next iteration leave the value of minimum index position and sort the minimum index position and sort the remaining values by following same steps.remaining values by following same steps.
Working of the selection Working of the selection sort :sort :
Say we have an array unsorted Say we have an array unsorted A[0],A[1],A[2]................ A[n-1] and A[n] as input. A[0],A[1],A[2]................ A[n-1] and A[n] as input. Then the following steps are followed by selection Then the following steps are followed by selection sort algorithm to sort the values of an array . (Say sort algorithm to sort the values of an array . (Say we have a key index_of_min that indicate the we have a key index_of_min that indicate the position of minimum value)position of minimum value)1.Initaily varaible index_of_min=0;1.Initaily varaible index_of_min=0;2.Find the minimum value in the unsorted array.2.Find the minimum value in the unsorted array.3.Assign the index of the minimum value into 3.Assign the index of the minimum value into index_of_min variable.index_of_min variable.4.Swap minimum value to first position.4.Swap minimum value to first position.5.Sort the remaining values of array (excluding 5.Sort the remaining values of array (excluding the first value).the first value).
Sample program in selection Sample program in selection sortsort
public class public class selectionSort{selectionSort{ public static void public static void main(String a[])main(String a[]){{ int int i;i; int int array[] = {12,9,4,99,120,1,3,1array[] = {12,9,4,99,120,1,3,10};0}; System.out.println("\n\ System.out.println("\n\n RoseIndia\n\n");n RoseIndia\n\n"); System.out.println(" Selection System.out.println(" Selection Sort\n\n"); Sort\n\n"); System.out.println("Values Before System.out.println("Values Before the sort:\n"); the sort:\n"); forfor(i = 0; i < array.length; i++)(i = 0; i < array.length; i++) System.out.print( array[i]+" "); System.out.print( array[i]+" "); System.out.println(); System.out.println(); selection_srt(array, array.length); selection_srt(array, array.length); System.out.print("Values after the System.out.print("Values after the sort:\n"); sort:\n"); forfor(i = 0; i <array.length; i++)(i = 0; i <array.length; i++) System.out.print(array[i]+" "); System.out.print(array[i]+" "); System.out.println(); System.out.println(); System.out.println("PAUSE"); System.out.println("PAUSE"); } }
public static void public static void selection_srt(selection_srt(iint nt array[], array[], int int n){n){ forfor((int int x=0; x<n; x++){x=0; x<n; x++){ int int index_of_min = x;index_of_min = x; forfor((int int y=x; y<n; y++){y=x; y<n; y++){ ifif(array[index_of_min]<array(array[index_of_min]<array[y]){[y]){ index_of_min = y; index_of_min = y; } } } } int int temp = array[x];temp = array[x]; array[x] = array[index_of_min array[x] = array[index_of_min];]; array[index_of_min] = temp; array[index_of_min] = temp; } } } }} }
ShellSortShellSort
ShellShell sort is a sorting algorithm that sort is a sorting algorithm that requires asymptotically fewer than O(n²) requires asymptotically fewer than O(n²) comparisons and exchanges in the comparisons and exchanges in the worst case. Although it is easy to worst case. Although it is easy to develop an intuitive sense of how this develop an intuitive sense of how this algorithm works, it is very difficult to algorithm works, it is very difficult to analyze its analyze its executionexecution time, but time, but estimates range from O(nlog2 n) to estimates range from O(nlog2 n) to O(n1.5) depending on implementation O(n1.5) depending on implementation details .details .
Shell sort improves insertion sort by comparing Shell sort improves insertion sort by comparing elements separated by a gap of several positions. elements separated by a gap of several positions. This lets an element take "bigger steps" toward This lets an element take "bigger steps" toward its expected position. Multiple passes over the its expected position. Multiple passes over the data are taken with smaller and smaller gap data are taken with smaller and smaller gap sizes. The last step of Shell sort is a plain sizes. The last step of Shell sort is a plain insertion sort, but by then, the array of data is insertion sort, but by then, the array of data is guaranteed to be almost sorted.guaranteed to be almost sorted.
Consider a small value that is initially stored in Consider a small value that is initially stored in the wrong end of the array. Using an O(n²) sort the wrong end of the array. Using an O(n²) sort such as bubble sort or insertion sort, it will take such as bubble sort or insertion sort, it will take roughly n comparisons and exchanges to move roughly n comparisons and exchanges to move this value all the way to the other end of the this value all the way to the other end of the array. Shell sort first moves values using giant array. Shell sort first moves values using giant step sizes, so a small value will move a long way step sizes, so a small value will move a long way towards its final position, with just a few towards its final position, with just a few comparisons and exchanges.comparisons and exchanges.
The Shell sort is named after its inventor, Donald The Shell sort is named after its inventor, Donald Shell, who Shell, who publishedpublished it in 1959. it in 1959.
Sample program in shell Sample program in shell sortsort
public class ShellSort {public class ShellSort { private long[] data; private long[] data;
private int len; private int len;
public ShellSort(int max) { public ShellSort(int max) { data = new long[max]; data = new long[max]; len = 0; len = 0; } }
public void insert(long value){ public void insert(long value){ data[len] = value; data[len] = value; len++; len++; } }
public void display() { public void display() { System.out.print("Data:"); System.out.print("Data:"); for (int j = 0; j < len; j++) for (int j = 0; j < len; j++) System.out.print(data[j] + " "); System.out.print(data[j] + " "); System.out.println(""); System.out.println(""); } }
public void shellSort() { public void shellSort() { int inner, outer; int inner, outer; long temp; long temp; //find initial value of h //find initial value of h int h = 1; int h = 1; while (h <= len / 3) while (h <= len / 3) h = h * 3 + 1; // (1, 4, 13, 40, 121, ...) h = h * 3 + 1; // (1, 4, 13, 40, 121, ...)
while (h > 0) // decreasing h, until h=1while (h > 0) // decreasing h, until h=1 { { // h-sort the file // h-sort the file for (outer = h; outer < len; outer++) { for (outer = h; outer < len; outer++) { temp = data[outer]; temp = data[outer]; inner = outer; inner = outer; // one subpass (eg 0, 4, 8) // one subpass (eg 0, 4, 8) while (inner > h - 1 && data[inner - h] > while (inner > h - 1 && data[inner - h] >= temp) {= temp) { data[inner] = data[inner - h]; data[inner] = data[inner - h]; inner -= h; inner -= h; } } data[inner] = temp; data[inner] = temp; } } h = (h - 1) / 3; // decrease h h = (h - 1) / 3; // decrease h } } } }
public static void main(String[] args) { public static void main(String[] args) { int maxSize = 10; int maxSize = 10; ShellSort arr = new ShellSort(maxSize); ShellSort arr = new ShellSort(maxSize);
for (int j = 0; j < maxSize; j++) { for (int j = 0; j < maxSize; j++) { long n = (int) (java.lang.Math.random() * long n = (int) (java.lang.Math.random() * 99);99); arr.insert(n); arr.insert(n); } } arr.display(); arr.display(); arr.shellSort(); arr.shellSort(); arr.display(); arr.display(); } }} }
Bidirectional Bubble Bidirectional Bubble SortSort
A alternative of bubble sort is bi-directional bubble A alternative of bubble sort is bi-directional bubble sort. The bi-directional bubble sort compares each sort. The bi-directional bubble sort compares each adjacent pair of elements in an array. The values will adjacent pair of elements in an array. The values will be swap if necessary. The values passes from the be swap if necessary. The values passes from the beginning to the end and also from the end to the beginning to the end and also from the end to the beginning. It stops when there is no any element to beginning. It stops when there is no any element to swap.swap.Bi-directional bubble sorting also known as Bi-directional bubble sorting also known as cocktail cocktail shakershaker sort, sort, shaker sortshaker sort, , double-directiondouble-direction bubble bubble sort. The complexity of bi-directional bubble sort is sort. The complexity of bi-directional bubble sort is O(n2).Bi-directional bubble sort is better than bubble O(n2).Bi-directional bubble sort is better than bubble sort. In Bi-directional bubble sort at least one sort. In Bi-directional bubble sort at least one elements is moved forward or backward to its place in elements is moved forward or backward to its place in the array with each pass. But in the case of bubble the array with each pass. But in the case of bubble sort moves elements by forward direction to its place, sort moves elements by forward direction to its place, but can only move elements backward in only one but can only move elements backward in only one location in each pass. location in each pass.
Working of bi-directional Working of bi-directional bubble sortbubble sort algorithm:algorithm:
Say we have an array unsorted Say we have an array unsorted A[0],A[1],A[2]............. A[n-1] and A[n] as input. A[0],A[1],A[2]............. A[n-1] and A[n] as input. Then the following steps are followed by bi-Then the following steps are followed by bi-directional bubble sort algorithm to sort the directional bubble sort algorithm to sort the values of an array.values of an array. 1.Compare A[0] &A[1] and A[n-1] & A[n] . 1.Compare A[0] &A[1] and A[n-1] & A[n] . 2.If A[0]>A[1] then Swap A[0] & A[1] and 2.If A[0]>A[1] then Swap A[0] & A[1] and
also if A[n-1]>A[n] then swap it.also if A[n-1]>A[n] then swap it. 3.Take next A[1] & A[2] and A[n-2] & A[n-1]. 3.Take next A[1] & A[2] and A[n-2] & A[n-1]. 4.Comapre these values. 4.Comapre these values. 5.If A[1]>A[2] then Swap A[1] & A[2] and 5.If A[1]>A[2] then Swap A[1] & A[2] and
also if A[n-2]>A[n-1] then swap also if A[n-2]>A[n-1] then swap it. it.
Stop:Stop: when there is no any pass for swap or the when there is no any pass for swap or the array values are in sorted order. array values are in sorted order.
Sample codeSample code public class public class BidirectionalBubbleSort{BidirectionalBubbleSort{
public static void public static void main(String a[]){main(String a[]){ int int i;i; int int array[] = {12,9,4,99,120,1,3,10array[] = {12,9,4,99,120,1,3,10};}; System.out.println("\n\ System.out.println("\n\n RoseIndia\n\n");n RoseIndia\n\n"); System.out.println(" Selection S System.out.println(" Selection Sort\n\n");ort\n\n"); System.out.println("Values Before th System.out.println("Values Before the sort:\n");e sort:\n"); forfor(i = 0; i < array.length; i++)(i = 0; i < array.length; i++) System.out.print( array[i]+" "); System.out.print( array[i]+" "); System.out.println(); System.out.println(); bidirectionalBubble_srt(array, array.l bidirectionalBubble_srt(array, array.length);ength); System.out.print("Values after the s System.out.print("Values after the sort:\n");ort:\n"); forfor(i = 0; i <array.length; i++)(i = 0; i <array.length; i++) System.out.print(array[i]+" "); System.out.print(array[i]+" "); System.out.println(); System.out.println(); System.out.println("PAUSE"); System.out.println("PAUSE"); } }
public static void public static void bidirectionalBubblbidirectionalBubble_srt(e_srt(int int array[], array[], int int n){n){ int int j;j; int int st = -1;st = -1; while while (st < n) {(st < n) { st++; st++; n--; n--; for for (j = st; j < n; j++) {(j = st; j < n; j++) { if if (array[j] > array[j + 1]) {(array[j] > array[j + 1]) { int int T = array[j];T = array[j]; array[j] = array[j + 1]; array[j] = array[j + 1]; array[j + 1] = T; array[j + 1] = T; } } } } for for (j = n; --j >= st;) {(j = n; --j >= st;) { if if (array[j] > array[j + 1]) {(array[j] > array[j + 1]) { int int T = array[j];T = array[j]; array[j] = array[j + 1]; array[j] = array[j + 1]; array[j + 1] = T; array[j + 1] = T; } } } } } } } }} }
Output of the example:Output of the example:
Extra Storage MergesortExtra Storage Mergesort
In extra storage merge sorting In extra storage merge sorting algorithm the unsorted values divide algorithm the unsorted values divide into two equal parts iteratively and into two equal parts iteratively and create an array for store data value in create an array for store data value in extra storage. Then merge the two extra storage. Then merge the two parts , sort it and store into an parts , sort it and store into an array .Then again merge the next part , array .Then again merge the next part , sort it and store into an array. Do it sort it and store into an array. Do it iteratively until the values are not in iteratively until the values are not in sorted order. In this sorting the number sorted order. In this sorting the number of elements must be even. of elements must be even.
Sample CodeSample Code public class public class ExtraStorageMergeSort{ExtraStorageMergeSort{
public static void public static void main(String a[]){main(String a[]){ int int i;i; int int array[] = {12,9,4,99,120,1,3,10array[] = {12,9,4,99,120,1,3,10};}; int int array1[] = array1[] = new intnew int[array.length[array.length];]; System.out.println("\n\ System.out.println("\n\n RoseIndia\n\n");n RoseIndia\n\n"); System.out.println(" Extra Strora System.out.println(" Extra Strorage Space Merge Sort\n\n");ge Space Merge Sort\n\n"); System.out.println("Values Before th System.out.println("Values Before the sort:\n");e sort:\n"); forfor(i = 0; i < array.length; i++)(i = 0; i < array.length; i++) System.out.print( array[i]+" "); System.out.print( array[i]+" "); System.out.println(); System.out.println(); mergeSort_srt(array,0, array.length- mergeSort_srt(array,0, array.length-1,array1);1,array1); System.out.print("Values after the s System.out.print("Values after the sort:\n");ort:\n"); forfor(i = 0; i <array.length; i++)(i = 0; i <array.length; i++) System.out.print(array1[i]+" "); System.out.print(array1[i]+" "); System.out.println(); System.out.println(); System.out.println("PAUSE"); System.out.println("PAUSE"); } }
public static void public static void mergeSort_srt(mergeSort_srt(int int ararray[], ray[], int int low, low, int int high, high, int int array1[]){array1[]){ ifif(low >= high) {(low >= high) { returnreturn;; } }
int int middle = (low+high) / 2;middle = (low+high) / 2; mergeSort_srt(array, low, middle, arra mergeSort_srt(array, low, middle, array1);y1); mergeSort_srt(array, middle+1, hig mergeSort_srt(array, middle+1, high, array1);h, array1); int int k, t_low = low, t_high = middlek, t_low = low, t_high = middle+1;+1; forfor(k = low; k <= high; k++)(k = low; k <= high; k++) if if ((t_low <= middle) && ((t_high((t_low <= middle) && ((t_high > high) || (array[t_low] < > high) || (array[t_low] < array[t_high]))) {array[t_high]))) { array1[k] = array[t_low++]; array1[k] = array[t_low++]; } } else else {{ array1[k] = array[t_high++]; array1[k] = array[t_high++]; } } forfor(k = low; k <= high; k++) {(k = low; k <= high; k++) { array[k] = array1[k]; array[k] = array1[k]; } } } }} }
Output for exampleOutput for example
Radix SortRadix Sort Radix sort is one of the nastiest sorts that I know. Radix sort is one of the nastiest sorts that I know.
This sort can be quite fast when used in This sort can be quite fast when used in appropriate context, however, to me, it seems that appropriate context, however, to me, it seems that the context is never appropriate for radix sort.the context is never appropriate for radix sort.
The idea behind the sort is that we sort The idea behind the sort is that we sort numbers according to their base (sort of). For numbers according to their base (sort of). For example, lets say we had a number 1024, and we example, lets say we had a number 1024, and we break it down into it's basic components. The 1 is break it down into it's basic components. The 1 is in the thousands, the 0 is in the hundreds, the 2 is in the thousands, the 0 is in the hundreds, the 2 is in the tens, and 4 is in some units. Anyway, given in the tens, and 4 is in some units. Anyway, given two numbers, we can sort them according to these two numbers, we can sort them according to these bases (i.e.: 100 is greater than 10 because first bases (i.e.: 100 is greater than 10 because first one has more 'hundreds').one has more 'hundreds').
Sample CodeSample Codeimport java.lang.*;import java.lang.*; import java.io.*; public class import java.io.*; public class
RadixSort{ public static void RadixSort{ public static void radixSort(int[] arr)radixSort(int[] arr)
{ if(arr.length == 0) { if(arr.length == 0) return; int[][] np = new int[arr.length][2]; return; int[][] np = new int[arr.length][2];
int[] q = new int[0x100]; int[] q = new int[0x100]; int i,j,k,l,f = 0;int i,j,k,l,f = 0; for(k=0;k<4;k++)for(k=0;k<4;k++){ for(i=0;i<(np.length-1);i++) { for(i=0;i<(np.length-1);i++) np[i][1] = i+1; np[i][1] = -1; np[i][1] = i+1; np[i][1] = -1;
for(i=0;i<q.length;i++) q[i] = -1; for(i=0;i<q.length;i++) q[i] = -1; for(f=i=0;i<arr.length;i++)for(f=i=0;i<arr.length;i++)
{ j = ((0xFF<<(k<<3))&arr[i])>>(k<<3); { j = ((0xFF<<(k<<3))&arr[i])>>(k<<3); If(q[j] == -1) l = q[j] = f; If(q[j] == -1) l = q[j] = f; else{ l = q[j]; else{ l = q[j]; while(np[l][1] != -1) l = np[l][1]; np[l][1] = while(np[l][1] != -1) l = np[l][1]; np[l][1] =
f; l = np[l][1]; } f = np[f][1]; np[l][0] = f; l = np[l][1]; } f = np[f][1]; np[l][0] = arr[i]; np[l][1] = -1; } arr[i]; np[l][1] = -1; } for(l=q[i=j=0];i<0x100;i++) for(l=q[i=j=0];i<0x100;i++) for(l=q[i];l!=-1;l=np[l][1]) arr[j++] = for(l=q[i];l!=-1;l=np[l][1]) arr[j++] = np[l][0]; } } np[l][0]; } }
public static void main(String[] args)public static void main(String[] args){ int i; int[] arr = new int[15]; { int i; int[] arr = new int[15]; System.out.print("original: "); System.out.print("original: "); for(i=0;i<arr.length;i++){ arr[i] = (int)for(i=0;i<arr.length;i++){ arr[i] = (int)(Math.random() * 1024); (Math.random() * 1024); System.out.print(arr[i] + " "); } System.out.print(arr[i] + " "); } radixSort(arr); System.out.print("\radixSort(arr); System.out.print("\nsorted: "); for(i=0;i<arr.length;i++) nsorted: "); for(i=0;i<arr.length;i++) System.out.print(arr[i] + " "); System.out.print(arr[i] + " "); System.out.println("\nDone ;-)"); } } System.out.println("\nDone ;-)"); } }
Output for exampleOutput for example
Original: 1023 1007 583 154 518 671 Original: 1023 1007 583 154 518 671 83 98 213 564 572 989 241 150 64 83 98 213 564 572 989 241 150 64
Sorted: 64 83 98 150 154 213 241 Sorted: 64 83 98 150 154 213 241 518 564 572 583 671 989 1007 1023 518 564 572 583 671 989 1007 1023
BogoSortBogoSort The archetypical perversely awful algorithm (as The archetypical perversely awful algorithm (as
opposed to opposed to bubble sortbubble sort, which is merely the , which is merely the generic generic badbad algorithm). Bogo-sort is equivalent to algorithm). Bogo-sort is equivalent to repeatedly throwing a deck of cards in the air, repeatedly throwing a deck of cards in the air, picking them up at random, and then testing picking them up at random, and then testing whether they are in order. It serves as a sort of whether they are in order. It serves as a sort of canonical example of awfulness. Looking at a canonical example of awfulness. Looking at a program and seeing a dumb algorithm, one might program and seeing a dumb algorithm, one might say “Oh, I see, this program uses bogo-sort.” Esp. say “Oh, I see, this program uses bogo-sort.” Esp. appropriate for algorithms with factorial or super-appropriate for algorithms with factorial or super-exponential running time in the average case and exponential running time in the average case and probabilistically infinite worst-case running time. probabilistically infinite worst-case running time.
Sample CodeSample Code//Sorts an integer array in ascending order. //Sorts an integer array in ascending order. ////
Notice that the array passed must not be a nNotice that the array passed must not be a null reference. ull reference.
//Parameters: //Parameters: // data - the integer array to sort // data - the integer array to sort //Postcondition: //Postcondition: // The array is sorted in ascending order. // The array is sorted in ascending order. //Warning: //Warning: // Due to the finite number of random sequences us// Due to the finite number of random sequences us
ed by ed by // java.util.Random it is possible that the execution // java.util.Random it is possible that the execution // of this code will result in an infinite loop. // of this code will result in an infinite loop. importimport java.util.Random; java.util.Random; publicpublic classclass BogoSort BogoSort { { privateprivate staticstatic finalfinal Random generator = Random generator = newnew Ra Ra
ndom(); ndom(); publicpublic staticstatic voidvoid bogoSort( bogoSort(intint[] data) [] data) { {
whilewhile (!isSorted(data)) { (!isSorted(data)) { forfor ( (intint i = 0; i < data.length; i++){ i = 0; i < data.length; i++){ intint randomPosition = generator.nextInt randomPosition = generator.nextInt
(data.length); (data.length); intint temp = data[i]; temp = data[i]; data[i] = data[randomPosition]; data[i] = data[randomPosition]; data[randomPosition] = temp; data[randomPosition] = temp; } } } } } } privateprivate staticstatic booleanboolean isSorted( isSorted(intint[] data) [] data) { { forfor ( (intint i = 1; i < data.length; i++) i = 1; i < data.length; i++) ifif (data[i] < data[i - 1]) (data[i] < data[i - 1]) returnreturn falsefalse; ; returnreturn truetrue; ; } } } }
IntroSortIntroSort Introsort introduces another change - the one that Introsort introduces another change - the one that
brings the introspective element into play. This is brings the introspective element into play. This is done by monitoring the recursion depth the done by monitoring the recursion depth the algorithm reaches as a function of the length of algorithm reaches as a function of the length of the array of data. Since the recursion depth for the array of data. Since the recursion depth for the best and worst case runtime are known a the best and worst case runtime are known a reasonable value in between can be calculated reasonable value in between can be calculated dynamically. This value acts as a threshold and dynamically. This value acts as a threshold and once it is exceeded Introsorts detects that the once it is exceeded Introsorts detects that the Quicksort algorithm it uses degenerates to Quicksort algorithm it uses degenerates to quadratic behaviour. The reaction to this is quadratic behaviour. The reaction to this is changing the sorting algorithm for the current changing the sorting algorithm for the current subarray of data. subarray of data.
Sample CodeSample Codepublic class Introsort implements Sorterpublic class Introsort implements Sorter{{ private static Sortable[] a;private static Sortable[] a; private static int size_threshold = 16;private static int size_threshold = 16;
public void sort(Sortable[] a0)public void sort(Sortable[] a0) {{ a=a0;a=a0; introsort_loop(0, a.length, 2*floor_lg(a.length));introsort_loop(0, a.length, 2*floor_lg(a.length)); insertionsort(0, a.length);insertionsort(0, a.length); }} public void sort(Sortable[] a0, int begin, int end)public void sort(Sortable[] a0, int begin, int end) {{ if (begin < end)if (begin < end) {{
a=a0;a=a0; introsort_loop(begin, end, 2*floor_lg(end-begin));introsort_loop(begin, end, 2*floor_lg(end-begin)); insertionsort(begin, end);insertionsort(begin, end);
}} }}
private static void introsort_loop (int lo, int hi, int depth_limit)private static void introsort_loop (int lo, int hi, int depth_limit) {{ while (hi-lo > size_threshold)while (hi-lo > size_threshold) {{ if (depth_limit == 0)if (depth_limit == 0) {{ heapsort(lo, hi);heapsort(lo, hi); return;return; }} depth_limit=depth_limit-1;depth_limit=depth_limit-1;
int p=partition(lo, hi, medianof3(lo, lo+((hi-lo)/2)+1, hi-1));int p=partition(lo, hi, medianof3(lo, lo+((hi-lo)/2)+1, hi-1)); introsort_loop(p, hi, depth_limit);introsort_loop(p, hi, depth_limit); hi=p;}hi=p;}
private static int partition(int lo, int hi, Sortable x)private static int partition(int lo, int hi, Sortable x) {{ int i=lo, j=hi;int i=lo, j=hi; while (true)while (true) {{ while (a[i].smaller(x)) i++;while (a[i].smaller(x)) i++; j=j-1;j=j-1; while (x.smaller(a[j])) j=j-1;while (x.smaller(a[j])) j=j-1; if(!(i < j))if(!(i < j)) return i;return i; exchange(i,j);exchange(i,j); i++;i++; }} }} private static Sortable medianof3(int lo, int mid, int hi)private static Sortable medianof3(int lo, int mid, int hi) {{ if (a[mid].smaller(a[lo]))if (a[mid].smaller(a[lo])) {{ if (a[hi].smaller(a[mid]))if (a[hi].smaller(a[mid])) return a[mid];return a[mid]; elseelse {{ if (a[hi].smaller(a[lo]))if (a[hi].smaller(a[lo]))
return a[hi];return a[hi];elseelse return a[lo];return a[lo];
}} }}
elseelse{{
if (a[hi].smaller(a[mid]))if (a[hi].smaller(a[mid])) {{ if (a[hi].smaller(a[lo]))if (a[hi].smaller(a[lo]))
return a[lo];return a[lo];elseelse return a[hi];return a[hi];
}} elseelse return a[mid];return a[mid];
}} }}
Binary Tree SortBinary Tree Sort
Binary tree work byBinary tree work by– Inserting items into a binary treeInserting items into a binary tree– Flattening the tree into a list or arrayFlattening the tree into a list or array
Sample CodeSample Code////// Binary_Tree_Sort.java// Binary_Tree_Sort.java// Binary Tree Sort// Binary Tree Sort////// Created by Kevin Bralten on 29/09/05.// Created by Kevin Bralten on 29/09/05.// Copyright (c) 2005 __MyCompanyName__. All rights // Copyright (c) 2005 __MyCompanyName__. All rights
reserved.reserved.////import java.util.*;import java.util.*;public class Binary_Tree_Sort {public class Binary_Tree_Sort { public static void main (String args[]) {public static void main (String args[]) { // inserted code here...// inserted code here...long n=0;long n=0;long t1 = 0,long t1 = 0,t2 = 0,t2 = 0,t3 = 0,t3 = 0,avg = 0,avg = 0,avgInsert = 0;avgInsert = 0; int maxItems = 5000000;int maxItems = 5000000;int nRuns=10;int nRuns=10;int stepSize=50000;int stepSize=50000;Random r=new Random();Random r=new Random();Item root;Item root;LinkedList list; System.out.println("n, total (ms), insert LinkedList list; System.out.println("n, total (ms), insert
(ms)");(ms)"); for(int k = 0; k <= maxItems; k+=stepSize)for(int k = 0; k <= maxItems; k+=stepSize)
{ // { // increment the number of itemsincrement the number of items
avg=avgInsert=0;avg=avgInsert=0; for (int j = 0; j < nRuns; j++){ //for (int j = 0; j < nRuns; j++){ //To sort the Array 10 times to find the averageTo sort the Array 10 times to find the averagelist=new LinkedList();list=new LinkedList();t1 = System.currentTimeMillis();t1 = System.currentTimeMillis(); root = new Item(r.nextInt());root = new Item(r.nextInt()); for (int i = 1; i < k; i++) {for (int i = 1; i < k; i++) { root.addItem(r.nextInt());root.addItem(r.nextInt());{ { t3 = System.currentTimeMillis();t3 = System.currentTimeMillis(); root.toList(list);root.toList(list); t2 = System.currentTimeMillis();t2 = System.currentTimeMillis(); avg += (t2 - t1);avg += (t2 - t1);avgInsert += (t3-t1);avgInsert += (t3-t1);{ { //System.out.println("Time for " + k + " //System.out.println("Time for " + k + "
items: items: " +(avg/10) + "ms");" +(avg/10) + "ms");System.out.println(k+", "+(avg/((float)nRuns))System.out.println(k+", "+(avg/((float)nRuns))+", "+(avgInsert/((float)nRuns)));+", "+(avgInsert/((float)nRuns)));{ { { {
Patience SortPatience Sort
Patience sortingPatience sorting is a is a sorting algorithmsorting algorithm, based on a , based on a solitairesolitaire card gamecard game, that has the , that has the property of being able to efficiently property of being able to efficiently compute the length of a compute the length of a longest increasing subsequencelongest increasing subsequence in a in a given array. given array.
Sample CodeSample Code import java.util.*;import java.util.*;
public class PatienceSortAlgorithm extends SortAlgorithm {public class PatienceSortAlgorithm extends SortAlgorithm {
public void sort (int [] n) throws Exceptionpublic void sort (int [] n) throws Exception {{ Vector piles = new Vector (0,1);Vector piles = new Vector (0,1); Vector first = new Vector (0,1);Vector first = new Vector (0,1); first.add(new Integer (n [0]));first.add(new Integer (n [0])); piles.add (first);piles.add (first); //sort into piles//sort into piles for (int a = 1; a < n.length; a++)for (int a = 1; a < n.length; a++) {{ boolean notFound = true;boolean notFound = true; for (int i = 0; i < piles.size () && notFound;i++)for (int i = 0; i < piles.size () && notFound;i++) {{ pause(a);pause(a); Vector pile = (Vector)(piles.get (i));Vector pile = (Vector)(piles.get (i)); int top = ((Integer)pile.get(pile.size ()-1)).intValue ();int top = ((Integer)pile.get(pile.size ()-1)).intValue (); if (top >= n [a])if (top >= n [a]) {{ pile.add (new Integer (n[a]));pile.add (new Integer (n[a])); notFound = false;notFound = false; }} }} if (notFound)if (notFound) {{
Vector newPile = new Vector (0,1);Vector newPile = new Vector (0,1); newPile.add (new Integer (n [a]));newPile.add (new Integer (n [a])); piles.add (newPile);piles.add (newPile); }} }}
int c = 0;int c = 0; while (c < n.length)while (c < n.length) {{ int small = 0;int small = 0; //find minimum value of top cards//find minimum value of top cards for (int a = 1; a < piles.size (); a ++)for (int a = 1; a < piles.size (); a ++) {{ pause(c);pause(c); Vector pile1 = (Vector)piles.get (a);Vector pile1 = (Vector)piles.get (a); Vector pile2 = (Vector)piles.get (small);Vector pile2 = (Vector)piles.get (small); int n1 = ((Integer)pile1.get (pile1.size ()-1)).intValue int n1 = ((Integer)pile1.get (pile1.size ()-1)).intValue
();(); int n2 = ((Integer)pile2.get (pile2.size ()-1)).intValue int n2 = ((Integer)pile2.get (pile2.size ()-1)).intValue
();(); if (n1 < n2)if (n1 < n2) {{ small = a;small = a; }} }} Vector smallPile = (Vector)piles.get (small);Vector smallPile = (Vector)piles.get (small); n [c] = ((Integer)smallPile.get (smallPile.size ()-n [c] = ((Integer)smallPile.get (smallPile.size ()-
1)).intValue ();1)).intValue (); smallPile.remove (smallPile.size ()-1);smallPile.remove (smallPile.size ()-1); if (((Vector)piles.get (small)).size () ==0)if (((Vector)piles.get (small)).size () ==0) {{ piles.remove (small);piles.remove (small); }} c++;c++; }} pause();pause();
}}
}}
Counting SortCounting Sort Counting sort is a linear time sorting algorithm used to sort items Counting sort is a linear time sorting algorithm used to sort items
when they belong to a fixed and finite set. Integers which lie in a when they belong to a fixed and finite set. Integers which lie in a fixed interval, say k1 to k2, are examples of such items.fixed interval, say k1 to k2, are examples of such items.
The algorithm proceeds by defining an ordering relation between The algorithm proceeds by defining an ordering relation between the items from which the set to be sorted is derived (for a set of the items from which the set to be sorted is derived (for a set of integers, this relation is trivial).Let the set to be sorted be called integers, this relation is trivial).Let the set to be sorted be called A. Then, an auxiliary array with size equal to the number of items A. Then, an auxiliary array with size equal to the number of items in the superset is defined, say B. For each element in A, say in the superset is defined, say B. For each element in A, say ee, the , the algorithm stores the number of items in A smaller than or equal algorithm stores the number of items in A smaller than or equal to to ee in B( in B(ee). If the sorted set is to be stored in an array C, then for ). If the sorted set is to be stored in an array C, then for each each ee in A, taken in reverse order, C[B[ in A, taken in reverse order, C[B[ee]] = ]] = ee. After each such . After each such step, the value of B(step, the value of B(ee) is decremented.) is decremented.
The algorithm makes two passes over A and one pass over B. If The algorithm makes two passes over A and one pass over B. If size of the range k is smaller than size of input n, then time size of the range k is smaller than size of input n, then time complexity=O(n). Also, note that it is a stable algorithm, meaning complexity=O(n). Also, note that it is a stable algorithm, meaning that ties are resolved by reporting those elements first which that ties are resolved by reporting those elements first which occur first.occur first.
This visual demonstration takes 8 randomly generated single digit This visual demonstration takes 8 randomly generated single digit numbers as input and sorts them. The range of the inputs are numbers as input and sorts them. The range of the inputs are from 0 to 9.from 0 to 9.
Sample CodeSample Code /* end is the last index + 1 *//* end is the last index + 1 */
public class CountingSortAlgorithm extends public class CountingSortAlgorithm extends SortAlgorithm {SortAlgorithm {
public void sort(int[] a) throws Exception {public void sort(int[] a) throws Exception { csort(a,128,0);csort(a,128,0); pause();pause(); }}
void csort(int array[], int max, int min) throws void csort(int array[], int max, int min) throws ExceptionException
{{ int i,j;int i,j; int range = max-min;int range = max-min; int[] count = new int[max-min+1];int[] count = new int[max-min+1]; int[] scratch = new int[array.length];int[] scratch = new int[array.length];
for(i = 0; i < range; i++) {for(i = 0; i < range; i++) { count[i] = 0;count[i] = 0; pause(i);pause(i); }}
/* /* * Set the value of count[i] to the number of* Set the value of count[i] to the number of * elements in array with value i+min-1. * elements in array with value i+min-1. */*/ for(i = 0; i < array.length; i++) {for(i = 0; i < array.length; i++) { int c = array[i]+1-min;int c = array[i]+1-min; count[c]++;count[c]++; pause(i,max-i);pause(i,max-i); }}
/* /* * Update count[i] to be the number of* Update count[i] to be the number of * elements with value less than i+min. * elements with value less than i+min. */*/ for (i = 1; i < count.length; i++)for (i = 1; i < count.length; i++) count[i] += count[i-1];count[i] += count[i-1];
/* /* * Copy the elements of array into scratch in* Copy the elements of array into scratch in * sorted order. * sorted order. */*/ for(i = 0; i < array.length; i++) {for(i = 0; i < array.length; i++) { int c = array[i]-min;int c = array[i]-min; int s = count[c];int s = count[c]; scratch[s] = array[i];scratch[s] = array[i]; /* /* * Increment count so that the next element* Increment count so that the next element * with the same value as the current element* with the same value as the current element * is placed into its own position in scratch. * is placed into its own position in scratch. */*/ count[c]++;count[c]++; }}
for(i = 0; i < array.length; i++)for(i = 0; i < array.length; i++) array[i] = scratch[i];array[i] = scratch[i]; }}
}}
Bucket SortBucket Sort
Bucket sortBucket sort, or , or bin sortbin sort, is a sorting , is a sorting algorithm that works by partitioning algorithm that works by partitioning an array into a number of buckets. Each an array into a number of buckets. Each bucket is then sorted individually, bucket is then sorted individually, either using a different sorting either using a different sorting algorithm, or by recursively applying algorithm, or by recursively applying the bucket sorting algorithm. It is the bucket sorting algorithm. It is a distribution sort, and is a cousin a distribution sort, and is a cousin ofradix sort in the most to least ofradix sort in the most to least significant digit flavour. Bucket sort is a significant digit flavour. Bucket sort is a generalization ofpigeonhole sort. generalization ofpigeonhole sort.
Sample CodeSample Code public class BucketSortAlgorithm extends SortAlgorithm {public class BucketSortAlgorithm extends SortAlgorithm {
public void sort(int[] a) throws Exception {public void sort(int[] a) throws Exception { int m=128;int m=128; int[] count = new int[m];int[] count = new int[m];
for (int i=0;i<m;++i) count[i]=0;for (int i=0;i<m;++i) count[i]=0; for (int j=0;j<a.length;++j) {for (int j=0;j<a.length;++j) { ++count[a[j]];++count[a[j]]; pause(j);pause(j); }} for (int i=0,j=0;i<m;++i)for (int i=0,j=0;i<m;++i) for (; count[i]>0;--count[i]) {for (; count[i]>0;--count[i]) { a[j++]=i;a[j++]=i; pause(i,j);pause(i,j); }} }}
}}
Odd-Even Transposition SortOdd-Even Transposition Sort
Odd even transposition sort is a parallel Odd even transposition sort is a parallel sorting algorithm. Odd Even is based on sorting algorithm. Odd Even is based on the Bubble Sort technique of comparing the Bubble Sort technique of comparing two numbers and swapping them and two numbers and swapping them and put higher value at larger index .In each put higher value at larger index .In each parallel computational steps can pair off parallel computational steps can pair off either the odd or even neighboring either the odd or even neighboring pairs. Each number (In Processing pairs. Each number (In Processing Element-PE) would look to it's right Element-PE) would look to it's right neighbor and if it were greater, it would neighbor and if it were greater, it would swap them. swap them.
Sample CodeSample Code public class public class OddEvenTranspositionSoOddEvenTranspositionSo
rt{rt{ public static void public static void main(String a[]){main(String a[]){ int int i;i; int int array[] = {12,9,4,99,120,1,3,10,array[] = {12,9,4,99,120,1,3,10,13};13}; System.out.println("\n\ System.out.println("\n\n RoseIndia\n\n");n RoseIndia\n\n"); System.out.println(" Odd Even T System.out.println(" Odd Even Transposition Sort\n\n");ransposition Sort\n\n"); System.out.println("Values Before th System.out.println("Values Before the sort:\n");e sort:\n"); forfor(i = 0; i < array.length; i++)(i = 0; i < array.length; i++) System.out.print( array[i]+" "); System.out.print( array[i]+" "); System.out.println(); System.out.println(); odd_even_srt(array,array.length); odd_even_srt(array,array.length); System.out.print("Values after the s System.out.print("Values after the sort:\n");ort:\n"); forfor(i = 0; i <array.length; i++)(i = 0; i <array.length; i++) System.out.print(array[i]+" "); System.out.print(array[i]+" "); System.out.println(); System.out.println(); System.out.println("PAUSE"); System.out.println("PAUSE"); } }
public static void public static void odd_even_srt(odd_even_srt(int int array[],int n){array[],int n){ for for ((int int i = 0; i < n/2; i++ ) {i = 0; i < n/2; i++ ) { for for ((int int j = 0; j+1 < n; j += 2)j = 0; j+1 < n; j += 2) if if (array[j] > array[j+1]) {(array[j] > array[j+1]) { int int T = array[j];T = array[j]; array[j] = array[j+1]; array[j] = array[j+1]; array[j+1] = T; array[j+1] = T; } } for for ((int int j = 1; j+1 < array.length; jj = 1; j+1 < array.length; j += 2) += 2) if if (array[j] > array[j+1]) {(array[j] > array[j+1]) { int int T = array[j];T = array[j]; array[j] = array[j+1]; array[j] = array[j+1]; array[j+1] = T; array[j+1] = T; } } } } } }} }
Gnome SortGnome Sort The simplest sort algorithm is not Bubble The simplest sort algorithm is not Bubble
Sort..., it is not Insertion Sort..., it's Gnome Sort..., it is not Insertion Sort..., it's Gnome Sort!Sort!
Gnome Sort is based on the technique used Gnome Sort is based on the technique used by the standard Dutch Garden Gnome (Du.: by the standard Dutch Garden Gnome (Du.: tuinkabouter). Here is how a garden gnome tuinkabouter). Here is how a garden gnome sorts a line of flower pots. Basically, he looks sorts a line of flower pots. Basically, he looks at the flower pot next to him and the at the flower pot next to him and the previous one; if they are in the right order he previous one; if they are in the right order he steps one pot forward, otherwise he swaps steps one pot forward, otherwise he swaps them and steps one pot backwards. them and steps one pot backwards. Boundary conditions: if there is no previous Boundary conditions: if there is no previous pot, he steps forwards; if there is no pot next pot, he steps forwards; if there is no pot next to him, he is done.to him, he is done.
Sample CodeSample Code
void gnomesort(int n, int ar[]) {void gnomesort(int n, int ar[]) {int i = 0;int i = 0;
while (i < n) {while (i < n) {if (i == 0 || ar[i-1] <= ar[i]) i++;if (i == 0 || ar[i-1] <= ar[i]) i++;else {int tmp = ar[i]; ar[i] = ar[i-1]; else {int tmp = ar[i]; ar[i] = ar[i-1];
ar[--i] = tmp;}ar[--i] = tmp;}}}
}}
Bozo SortBozo Sort
BogosortBogosort (also (also random sortrandom sort, , shotgun shotgun sortsort or or monkey sortmonkey sort) is a particularly ) is a particularly ineffective sorting algorithm. Its only use is ineffective sorting algorithm. Its only use is for educational purposes, to contrast it with for educational purposes, to contrast it with other more realistic algorithms. If bogosort other more realistic algorithms. If bogosort were used to sort a deck of cards, it would were used to sort a deck of cards, it would consist of checking if the deck were in consist of checking if the deck were in order, and if it were not, throwing the deck order, and if it were not, throwing the deck into the air, picking the cards up at random, into the air, picking the cards up at random, and repeating the process until the deck is and repeating the process until the deck is sorted. Its name comes from the sorted. Its name comes from the word word bogusbogus. .
Sample CodeSample Code
class BozoSortAlgorithm extends SortAlgorithm {class BozoSortAlgorithm extends SortAlgorithm {
void sort(int a[]) throws Exception {void sort(int a[]) throws Exception {
boolean sorted = false;boolean sorted = false;
while (!sorted) {while (!sorted) { int index1 = Randomize(a.length);int index1 = Randomize(a.length); int index2 = Randomize(a.length);int index2 = Randomize(a.length);
int temp = a[index2];int temp = a[index2]; a[index2] = a[index1];a[index2] = a[index1]; a[index1] = temp;a[index1] = temp; pause(index1, index2);pause(index1, index2); //pause();//pause(); // Is a[] sorted?// Is a[] sorted?
sorted = true;sorted = true; for (int i = 1; i < a.length; i++) {for (int i = 1; i < a.length; i++) {
if (a[i-1] > a[i]) {if (a[i-1] > a[i]) { pause(i, i-1);pause(i, i-1); //pause();//pause(); sorted = false;sorted = false; break;break;} // end if} // end if
} // end for} // end for} // end while} // end while
} // end sort} // end sort
private int Randomize( int range ) {private int Randomize( int range ) {
double rawResult;double rawResult;
rawResult = Math.random();rawResult = Math.random();return (int) (rawResult * range);return (int) (rawResult * range);
}}
} // end BozoSortAlgorithm} // end BozoSortAlgorithm
Stooge SortStooge Sort
A terribly inefficient A terribly inefficient sortsort algorithm algorithm that swaps the top and bottom items that swaps the top and bottom items if needed, then (if needed, then (recursivelyrecursively) sorts the ) sorts the bottom two-thirds, then the top two-bottom two-thirds, then the top two-thirds, then the bottom two-thirds thirds, then the bottom two-thirds again. again.
Sample CodeSample Code class StoogeSortAlgorithm extends SortAlgorithm {class StoogeSortAlgorithm extends SortAlgorithm { void sort(int a[], int lo, int hi) throws Exception {void sort(int a[], int lo, int hi) throws Exception { if(a[lo] > a[hi]) {if(a[lo] > a[hi]) { int T = a[lo];int T = a[lo]; a[lo] = a[hi];a[lo] = a[hi]; a[hi] = T;a[hi] = T; }} //compex(lo,hi);//compex(lo,hi); pause(lo,hi);pause(lo,hi); if(lo + 1 >= hi)if(lo + 1 >= hi) return;return; int third = (hi - lo + 1) / 3;int third = (hi - lo + 1) / 3; sort(a, lo, hi-third);sort(a, lo, hi-third); sort(a, lo+third, hi);sort(a, lo+third, hi); sort(a, lo, hi-third);sort(a, lo, hi-third); }}
void sort(int a[]) throws Exception {void sort(int a[]) throws Exception { sort(a, 0, a.length-1);sort(a, 0, a.length-1); }} }}
Several Unique SortSeveral Unique Sort
Several UniqueSeveral Unique is a sorting is a sorting algorithm that works by pushing algorithm that works by pushing elements to their final place. It was elements to their final place. It was found by the Critticall programming found by the Critticall programming tool, which uses evolutionary tool, which uses evolutionary programming to optimise existing programming to optimise existing algorithms. algorithms. Several UniqueSeveral Unique operates operates fastest when the input arrays have a fastest when the input arrays have a small number of unique elements small number of unique elements among a larger number of them. among a larger number of them.
Sample CodeSample Code public class SeveralUniqueSortAlgorithm extends public class SeveralUniqueSortAlgorithm extends
SortAlgorithm {SortAlgorithm {
public void sort (int[] Element) throws Exception {public void sort (int[] Element) throws Exception {
int EndIndex; /* Index where current scan should int EndIndex; /* Index where current scan should end. */end. */
int Position; /* Current scan position. */int Position; /* Current scan position. */ int HighValue; /* Highest value found in current int HighValue; /* Highest value found in current
scan. */scan. */ int SwapIndex = 0; /* First index of highest value int SwapIndex = 0; /* First index of highest value
found. */found. */ int NewValue; /* Value of current element. */int NewValue; /* Value of current element. */
/* Scan all elements on the first pass. *//* Scan all elements on the first pass. */ EndIndex = Element.length - 1;EndIndex = Element.length - 1;
/* For each distinct element value... *//* For each distinct element value... */ dodo {{ /* Start with no highest value (use lowest possible /* Start with no highest value (use lowest possible
value). */value). */ HighValue = 0;HighValue = 0;
/* For each element, scanning from start to end... *//* For each element, scanning from start to end... */ Position = -1;Position = -1; while ( Position < EndIndex )while ( Position < EndIndex ) {{ //pause(Position, //pause(Position,
EndIndex);EndIndex); /* Advance to the next element. *//* Advance to the next element. */ Position++;Position++;
/* Get the current value. *//* Get the current value. */ NewValue = Element[ Position ];NewValue = Element[ Position ];
}} /* If the current value is lower, swap it with highest so far./* If the current value is lower, swap it with highest so far. * Rather than swapping the lower value again, use the * Rather than swapping the lower value again, use the
nextnext * position which is the first occurrence of the highest * position which is the first occurrence of the highest
value. */value. */ if ( NewValue < HighValue )if ( NewValue < HighValue ) {{ Element[ SwapIndex ] = NewValue;Element[ SwapIndex ] = NewValue; SwapIndex++;SwapIndex++; Element[ Position ] = HighValue;Element[ Position ] = HighValue; }}
/* If the current value is higher, remember its /* If the current value is higher, remember its value/position. */value/position. */
if ( NewValue > HighValue )if ( NewValue > HighValue ) {{ SwapIndex = Position;SwapIndex = Position; HighValue = Element[ Position ];HighValue = Element[ Position ]; }} pause(Position, EndIndex);pause(Position, EndIndex); }}
/* Finish the next scan prior to the highest value found in /* Finish the next scan prior to the highest value found in this pass,this pass,
* as its elements are now in their final positions. */* as its elements are now in their final positions. */ EndIndex = SwapIndex - 1;EndIndex = SwapIndex - 1; }} while ( Position >= SwapIndex );while ( Position >= SwapIndex );
}}