1、排序定义
2、内排序方法
主要有插入排序、交换排序、选择排序和归并排序,这里着重介绍插入排序和交换排序。
插入排序又可以细分为直接插入排序、折半插入排序、链表插入排序、shell(希尔)排序等。
交换排序可以分为“起泡”排序和“快速”排序
3、快速排序的实现
//自己实现的快速排序
#include <stdio.h>
#include <stdlib.h>
#define N 15
int partion(int *data, int low, int high);
int quick_sort(int *data, int low, int high);
int main(int argc, const char *argv[])
{
int data[N] = {0};
int i;
srandom(10);
for (i = 0; i < N; i++) {
data[i] = random() % 100;
}
for (i = 0; i < N; i++) {
printf("%d ", data[i]);
}
puts("");
quick_sort(data, 0, N-1);
for (i = 0; i < N; i++) {
printf("%d ", data[i]);
}
puts("");
return 0;
}
int partion(int *data, int low, int high) {
int temp = data[low];
while (low < high) {
while (low < high && temp <= data[high]) {
high--;
}
data[low] = data[high];
while (low < high && temp >= data[low]){
low++;
}
data[high] = data[low];
}
data[low] = temp;
return low;
}
int quick_sort(int *data, int low, int high) {
int t;
if (data == NULL) {
return -1;
}
if (low >= high)
return 0;
t = partion(data, low, high);
quick_sort(data, low, t-1);
quick_sort(data, t+1, high);
return 0;
}
//调用库里面的快速排序函数
#include <stdio.h>
#include <stdlib.h>
#define N 15
int partion(int *data, int low, int high);
int quick_sort(int *data, int low, int high);
int compare(const void *p1, const void *p2);
int main(int argc, const char *argv[])
{
int data[N] = {0};
int i;
srandom(10);
for (i = 0; i < N; i++) {
data[i] = random() % 100;
}
for (i = 0; i < N; i++) {
printf("%d ", data[i]);
}
puts("");
//quick_sort(data, 0, N-1);
qsort(data, N, sizeof(int), compare);
for (i = 0; i < N; i++) {
printf("%d ", data[i]);
}
puts("");
return 0;
}
int partion(int *data, int low, int high) {
int temp = data[low];
while (low < high) {
while (low < high && temp <= data[high]) {
high--;
}
data[low] = data[high];
while (low < high && temp >= data[low]){
low++;
}
data[high] = data[low];
}
data[low] = temp;
return low;
}
int quick_sort(int *data, int low, int high) {
int t;
if (data == NULL) {
return -1;
}
if (low >= high)
return 0;
t = partion(data, low, high);
quick_sort(data, low, t-1);
quick_sort(data, t+1, high);
return 0;
}
int compare(const void *p1, const void *p2) {
return (*(const int *)p1 - *(const int *)p2);
}
出错记录
1、结果打印不整洁
原因:没有在for循环输出后加puts()函数
错误打印
正确打印
2、segmentation fault (core dumped)
原因:在quick_sort函数中,没有让程序跳出递归条件
解决方式:在partion函数前加入递归结束条件