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
|
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define SIZE 100
//从小到大排序
int comp1( const void *x, const void *y)
{
return *( int *)x - *( int *)y;
}
//从大到小排序
int comp2( const void *x, const void *y)
{
return *( int *)y - *( int *)x;
}
void main()
{
int arr[SIZE];
int n = 0; //数组的有效长度
int t = 0;
int i;
printf ( "input the arr(Q to quit).\n" );
while ( (t = scanf ( "%d" ,&arr[n])) != 0)
{
n++;
}
printf ( "arr before qsort.\n" );
for (i = 0; i < n; i++)
{
printf ( "arr[%d]=%d\t" ,i,arr[i]);
if ((i+1) % 5 == 0)
{
printf ( "\n" );
}
}
qsort (arr,n, sizeof ( int ),comp1);
printf ( "\narr after qsort.\n" );
for (i = 0; i < n; i++)
{
printf ( "arr[%d]=%d\t" ,i,arr[i]);
if ((i+1) % 5 == 0)
{
printf ( "\n" );
}
}
qsort (arr,n, sizeof ( int ),comp2);
printf ( "\nRecover All.\n" );
for (i = 0; i < n; i++)
{
printf ( "arr[%d]=%d\t" ,i,arr[i]);
if ((i+1) % 5 == 0)
{
printf ( "\n" );
}
}
printf ( "\n" );
}
|
只带两个参数的快速排序:
编写快速排序,函数qsort(),函数只带两个参数
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
|
#include<stdio.h>
#include<time.h>
#include<stdlib.h>
#define LEN 10
typedef int dataType;
//初始化数组,数组元素为小于100的整数
void intiArr(dataType A[], int len);
//打印数组元素
void print(dataType A[], int len);
//带两个参数的快排
void qsort (dataType A[], int len);
int main()
{
dataType data[LEN];
intiArr(data,LEN);
printf ( "排序前数组元素:" );
print(data,LEN);
qsort (data,LEN);
printf ( "排序后数组元素:" );
print(data,LEN);
return 0;
}
|
初始化数组,数组元素为小于100的整数
1
2
3
4
5
6
7
8
9
|
void intiArr(dataType A[], int len)
{
int i;
srand ((unsigned) time (NULL));
for (i = 0; i < len; i++)
{
A[i] = rand () % 100;
}
}
|
打印数组元素
1
2
3
4
5
6
7
8
9
10
11
|
void print(dataType A[], int len)
{
int i;
for (i = 0; i < len; i++)
{
if (i % 5 == 0)
printf ( "\n" );
printf ( "%d\t" ,A[i]);
}
printf ( "\n" );
}
|
带两个参数的快排
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
|
void qsort (dataType A[], int len)
{
dataType *p = A;
dataType *q = A + len - 1;
dataType temp = *p;;
if (len <= 0)
{
return ;
}
while (p < q)
{
while ((p < q) && (*q >= temp))
{
q--;
}
*p = *q;
while ((p < q) && (*p <= temp))
{
p++;
}
*q = *p;
}
*p = temp;
qsort (A,p - A);
qsort (p + 1,len - (p - A) - 1);
}
|