冒泡
1 static void BubbleSort() 2 { 3 int[] array = new int[] { 7, 3, 5, 8, 2 }; 4 5 for (int i = 0; i < array.Length; i++) 6 { 7 for (int j = 0; j < array.Length - i - 1; j++) 8 { 9 if (array[j] > array[j + 1]) 10 { 11 int temp = array[j]; 12 array[j] = array[j + 1]; 13 array[j + 1] = temp; 14 } 15 } 16 } 17 Array.ForEach(array, p => Console.Write(p)); 18 }
快排
static int QuickSort(int[] array, int low, int high) { if (low >= high) return -1; int keyIndex = low; int key = array[low]; while (low < high) { while (low <= high) { if (key > array[high]) { Swap(array, keyIndex, high); keyIndex = high; break; } high--; } while (low < high) { if (key < array[low]) { Swap(array, low, keyIndex); keyIndex = low; break; } low++; } } return keyIndex; } static void QuickSortRecursion(int[] array, int i, int j) { int index = QuickSort(array, i, j); if (index == -1) return; QuickSortRecursion(array, i, index - 1); QuickSortRecursion(array, index + 1, j); }
二分
1 static int DichoFind(int[] array, int num) 2 { 3 int i = 0; 4 int j = array.Length - 1; 5 6 while (i <= j) 7 { 8 int mid = (i + j) / 2; 9 10 if (array[mid] > num) 11 { 12 j = mid - 1; 13 } 14 else if (array[mid] < num) 15 { 16 i = mid + 1; 17 } 18 else 19 { 20 return mid; 21 } 22 } 23 24 return -1; 25 }