-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathqsort.c
79 lines (67 loc) · 1.16 KB
/
qsort.c
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
69
70
71
72
73
74
75
76
77
78
79
#include <stdio.h>
#include <stdlib.h>
void swap(int *a, int *b);
void sort(int *a, unsigned int start, unsigned int end);
int main(void)
{
unsigned int size = 10;
int a[size];
srand((unsigned)time(NULL));
for(int i =0; i < size; i++)
{
a[i] = rand();
printf("%d : %d\n", i, a[i]);
}
sort(a, 0, size - 1);
for(int i = 0; i < size; i++)
{
printf("%d : %d\n", i, a[i]);
}
}
void swap(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}
void sort(int *a, unsigned int start, unsigned int end)
{
int pivot = a[start];
int idx_start = start;
int idx_end = end;
int line;
while(idx_start < idx_end)
{
// 左からpivot以上の整数を探す
while(idx_start < idx_end)
{
line = idx_start;
if(pivot <= a[idx_start])
{
break;
}
idx_start++;
}
// 右からpivot未満の整数を探す
while(idx_start < idx_end)
{
if(pivot > a[idx_end])
{
break;
}
idx_end--;
}
if(idx_start < idx_end)
{
swap(&a[idx_start], &a[idx_end]);
}
}
if(start < line)
{
sort(a, start, line);
}
if(line + 1 < end)
{
sort(a, line + 1, end);
}
}