算法-快排
体会轴的概念
先做一个方法,定义一个数组,以最后一个数为轴,把比轴小的数放在轴的左边,比轴大的数放在轴的右边
1 public static void LastAxleSort(int[]arr,int leftB,int rightB) 2 { 3 4 5 int left = leftB; 6 int last = rightB; 7 int right = rightB-1; 8 9 10 while (left <right) 11 { 12 while (arr[left] <= arr[last] && left < right) 13 { 14 left++; 15 } 16 17 while (arr[right] >= arr[last] && left < right) 18 { 19 right--; 20 } 21 22 if (left < right) 23 { 24 ExchangeLocation(arr, left, right); 25 } 26 else if (left==right) 27 { 28 break; 29 } 30 31 } 32 33 if (left<last&& arr[left]>arr[last]) 34 { 35 ExchangeLocation(arr, left, last); 36 } 37 38 }
扩展为取数组的一部分
1 public static int LastAxleSortPart1(int[] arr, int leftB, int rightB) 2 { 3 4 5 int left = leftB; 6 int last = rightB; 7 int right = rightB - 1; 8 9 int lastValue = arr[last]; 10 11 12 while (left < right) 13 { 14 while (arr[left] <= arr[last] && left <= right) 15 { 16 left++; 17 } 18 19 while (arr[right] >= arr[last] && left < right) 20 { 21 right--; 22 } 23 24 if (left < right) 25 { 26 ExchangeLocation(arr, left, right); 27 } 28 29 30 } 31 32 if (left < last&& arr[left]>arr[last]) 33 { 34 ExchangeLocation(arr, left, last); 35 } 36 //Console.WriteLine(); 37 //Console.WriteLine($"左边界:{leftB},右边界:{rightB},排序轴值:{lastValue},返回轴:{left}"); 38 //PrintArr(arr); 39 return left; 40 41 }
递归调用的方法
1 public static void QuickSortPart(int[] arr,int leftB,int rightB) 2 { 3 if (leftB>=rightB) 4 { 5 return; 6 } 7 int axle = LastAxleSortPart1(arr, leftB, rightB); 8 9 10 QuickSortPart(arr, leftB, axle-1); 11 QuickSortPart(arr, axle+1, rightB); 12 13 //Console.WriteLine($"**"); 14 15 }