找到数组中第几个最小的数据 将经典的快速排序算法做简单修改即可
示例代码如下:
void testFindSpecificMin(){
int arr[] = {2, 4, 3, 9, 6, 5, 7, 0, 2, 1};
//int arr[] = {4, 2, 9};
//int arr[] = {0, 1, 2, 3, 4, 5, 6, 7, 8};
int position = 2;
findSpecificMin(arr, sizeof(arr)/sizeof(int), position - 1, 0);
printf("\n");
for (int i = 0; i < sizeof(arr)/sizeof(int); i++) {
printf("arr is %d\n", arr[i]);
}
printf("min is %d\n", arr[position - 1]);
for (int i = 1; i <= sizeof(arr)/sizeof(int); i++) {
int position = i;
findSpecificMin(arr, sizeof(arr)/sizeof(int), position - 1, 0);
printf("min is %d\n", arr[position - 1]);
}
}
/**
* currentPivot 当前枢纽元的位置
* specificMin 第几个最小的数
*/
void findSpecificMin(int arr[], int length, int specificMin, int currentPivot){
if (length <= 1) {
return;
}
if (length == 2) {
if (arr[0] > arr[1]) {
swap(arr, arr + 1);
}
return;
}
int center = (length - 1) / 2;
if (arr[0] > arr[length - 1]) {
swap(arr, arr + length - 1);
}
if (arr[0] > arr[center]) {
swap(arr, arr + center);
}
if (arr[center] > arr[length - 1]) {
swap(arr + center, arr + length - 1);
}
swap(arr + center, arr + length - 1);
int pivotElement = arr[length - 1];
int leftp = 0;
int rightp = length - 1;
while (1) {
while (arr[--rightp] > pivotElement) {
}
while (arr[++leftp] < pivotElement) {
}
if (rightp > leftp) {
swap(arr + rightp, arr + leftp);
}else{
break;
}
}
swap(arr + leftp, arr + length - 1);
printf("\n");
for (int i = 0; i < length; i++) {
printf("arr is %d\n", arr[i]);
}
if (currentPivot + leftp <= specificMin) {
findSpecificMin(arr + leftp, length - leftp, specificMin, currentPivot + leftp);
}else{
findSpecificMin(arr, leftp, specificMin, currentPivot);
}
}