Overview of many sorting techniques and sample code.
Insertion Sort
If you are asked to do the Insertion sort you can follow the code:
public static int[] InsertionSort(int[] a) { for (int i = 1; i < a.Length; i++) { int k = i; while (a[k] < a[k - 1] && k > 0) { int temp = a[k]; a[k] = a[k - 1]; a[k - 1] = temp; k--; } } return a; } |
Selection Sort
If you are asked to write Selection Sort you can follow the code:
public static int[] SelectionSort(int[] a) { for (int i = 0; i < a.Length; i++) { int min = i; for (int j = i; j < a.Length; j++) { if (a[min] > a[j]) { min = j; } } if (i != min) { int temp = a[min]; a[min] = a[i]; a[i] = temp; } } return a; } |
Bubble Sort
public static int[] BubbleSort(int[] a) { for (int i = 0; i < a.Length; i++) { for (int j = 0; j < a.Length; j++) { if (a[i] < a[j]) { int temp = a[i]; a[i] = a[j]; a[j] = temp; } } } return a; } |

Leave a Reply
You must be logged in to post a comment.