这个是升序排列,如果想降序排列,将下面两行的符号反过来即可;
arr[right] <= arr[key]
arr[left] >= arr[key]
代码工程
#define _CRT_SECURE_NO_WARNINGS
#include
void swap(int *v1, int *v2)
{
int temp = *v1;
*v1 = *v2;
*v2 = temp;
}
void my_qsort(int *arr, int start, int end)
{
int key = start;
int left = start;
int right = end;
if (left > right)
{
return;
}
while (left < right)
{
while ((left < right) && (arr[right] >= arr[key]))
{
right--;
}
while ((left < right) && (arr[left] <= arr[key]))
{
left++;
}
swap(&arr[left], &arr[right]);
}
swap(&arr[key], &arr[right]);
key = right;
my_qsort(arr, start, key - 1);
my_qsort(arr, key + 1, end);
return;
}
int main()
{
int i = 0;
int arr[] = { 10, 6, 9, 1, 8, 7, 5, 4, 2, 3 };
int num = sizeof(arr) / sizeof(int);
my_qsort(arr, 0, num - 1);
printf("排序后:");
for (i = 0; i < num; i++)
{
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
运行结果