题目:随机产生10个0-9的整数,用快速排序法对其进行排序。(升序)
算法分析:
- 基本思想为:通过一趟排序将待排序的序列分割为前后两个部分,其中一部分序列中的数据比另一部分序列中的数据小。然后分别对这前后两部分的数据用同样的方法进行排序,直到整个序列有序为止。
C代码:
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<time.h>
void QuickSort(int array[], int start, int end) {
int low = start, high = end;
int target = array[low];//基数
if (low < high) {
while (low < high) {
//从右向左找比基数小的
while (low < high&&array[high] > target) {
high--;
}
//填坑
if (low < high) {
array[low] = array[high];
low++;
}
//从左往右找比基数大的
while (low < high&&array[low] < target) {
low++;
}
//填坑
if (low < high) {
array[high] = array[low];
high--;
}
}
//循环结束后,low和high指向同一个位置,将target放在该位置处
array[low] = target;
QuickSort(array, start, low - 1);
QuickSort(array, low + 1, end);
}
}
void PrintArray(int array[], int n) {
for (int i = 0; i < n; i++) {
printf("%d ", array[i]);
}
printf("\n");
}
int main() {
int array[10];
int n = sizeof(array) / sizeof(array[0]);
srand((unsigned int)time(NULL));
for (int i = 0; i < n; i++) {
array[i] = rand() % 10;
}
printf("快速排序前:");
PrintArray(array, n);
QuickSort(array, 0, n - 1);
printf("快速排序后:");
PrintArray(array, n);
return 0;
}
C运行结果:C++代码:
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<ctime>
using namespace std;
void Swap(int *a, int *b) {
int temp = 0;
temp = *a;
*a = *b;
*b = temp;
}
void QuickSort(int array[], int start, int end) {
int low, high;
int target = array[start];//基准数
if (start < end) {
low = start;
high = end + 1;
while (1) {
do {
low++;
} while (array[low] <= target&&low != end);
do {
high--;
} while (array[high] >= target&&high != start);
if (low < high) {
Swap(&array[low], &array[high]);
}
else {
break;
}
}
Swap(&array[start], &array[high]);
QuickSort(array, start, high - 1);
QuickSort(array, high + 1, end);
}
}
void PrintArray(int array[], int n) {
for (int i = 0; i < n; i++) {
cout << array[i] << " ";
}
cout << endl;
}
int main() {
int array[10];
int n = sizeof(array) / sizeof(array[0]);
srand((unsigned int)time(NULL));
for (int i = 0; i < n; i++) {
array[i] = rand() % 10;
}
cout << "快速排序前:";
PrintArray(array, n);
QuickSort(array, 0, n - 1);
cout << "快速排序后:";
PrintArray(array, n);
return 0;
}
C++运行结果: