public void Set(int index, int val) { if (index < 0 || index >= len) { return; } data[index] = val; //使用快排,保持有序 TestChapter12.QuickSort(data); }
public void Add(int val) { if (len >= cap) { return; } data[len] = val; len++; //使用快排,保持有序 TestChapter12.QuickSort(data); }
static public void BucketSortExample() { //对这组金额在0-50之间的订单进行桶排序 int[] arr = { 22, 5, 11, 41, 45, 26, 29, 10, 7, 8, 30, 27, 42, 43, 40 }; //设置5个桶,0-9,10-19,20-29,30-30,40-49,一个桶的容量为arr.Length int[,] buckets = new int[5, arr.Length]; int[] lengthOfBuckets = new int[5]; for (int i = 0; i < arr.Length; i++) { int index = arr[i] / 10; buckets[index, lengthOfBuckets[index]] = arr[i]; lengthOfBuckets[index]++; } int[] temp = new int[arr.Length]; //针对桶内元素进行快速排序 int startIndexOfArr = 0; for (int i = 0; i < buckets.GetLength(0); i++) { int len = lengthOfBuckets[i]; if (len == 0) { //跳过空桶 continue; } for (int j = 0; j < len; j++) { temp[j] = buckets[i, j]; } TestChapter12.QuickSort(temp); for (int j = 0; j < len; j++) { arr[startIndexOfArr + j] = temp[j]; } startIndexOfArr += len; } PrintArr(arr); }