Created
September 26, 2013 02:13
-
-
Save wszdwp/6708927 to your computer and use it in GitHub Desktop.
Sorting-insertionSort, shellSort, BubbleSort
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public class Sorting | |
| { | |
| public static void insertionSort(int[] a) { | |
| for(int index = 1; index < a.length; index++) { | |
| int key = a[index]; | |
| int position = index; | |
| while( position > 0 && a[ position - 1] > key ) { | |
| a[position] = a[position - 1]; | |
| position--; | |
| } | |
| a[position] = key; | |
| } | |
| } | |
| public static void shellSort(int[] a) { | |
| int N = a.length; | |
| int h = 1; | |
| while( h < N/3) h = 3 * h + 1; //1, 4, 13, 40, 121, 364 | |
| while( h >= 1) | |
| { | |
| for(int i = h; i < N; i++) { | |
| for(int j = i; (j >=h) && (a[j - h] > a[j]); j-=h) { | |
| int tmp = a[j]; | |
| a[j] = a[ j - h ]; | |
| a[ j - h ] = tmp; | |
| } | |
| } | |
| h = h / 3; | |
| } | |
| } | |
| public static void bubbleSort(int[] a) { | |
| int tmp; | |
| for(int j = a.length - 1; j > 0; j--) { | |
| for (int i = 0; i < j; i++) { | |
| if( a[i] > a[ i + 1]) { | |
| tmp = a[i + 1]; | |
| a[i + 1] = a[i]; | |
| a[i] = tmp; | |
| } | |
| } | |
| } | |
| } | |
| public static void main(String[] args){ | |
| int[] c = {4,9,23,1,45,27,5,2}; | |
| //insertionSort(c); | |
| //bubbleSort(c); | |
| shellSort(c); | |
| for(int i=0;i<c.length;i++) | |
| System.out.print(c[i] + ", "); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment