summaryrefslogtreecommitdiff
path: root/c/dataStructure/sorting/quickSort.c
blob: 2904b481499fae7e587bd81c5cf02a4c7d4326bd (plain)
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
#include<stdio.h>
#include<stdlib.h>
#include<time.h>

#define SIZE 10

void swap(int * a, int * b)
{
	int tmp = *a;
	*a = *b;
	*b = tmp;
}

void generateRandom(int * arr, int n)
{
	time_t sr;
	srand(sr);

	for(int i = 0; i < n; i++)
		arr[i] = rand() % 100;
}

int partition(int * arr, int low, int high)
{
	int i,j;
	for (i = low, j = low; i < high; i++)
		if (arr[i] < arr[high])
		{
			swap(&arr[i],&arr[j]);
			j++;
		}
	swap(&arr[high],&arr[j]);

	return j;
}

void quickSort(int * arr, int low, int high)
{
	if (low < high)
	{
		int pivot = partition(arr,low,high);
		quickSort(arr,low, pivot - 1);	// sort left
		quickSort(arr,pivot + 1, high);
	}
}

int main(void)
{
	int arr[SIZE];
	generateRandom(arr,SIZE);

	for(int i = 0; i < SIZE; i++)
		printf("%3d",*(arr+i));
	putchar('\n');

	quickSort(arr,0,SIZE - 1);

	for (int i = 0; i < SIZE; i++)
		printf("%3d",arr[i]);
	putchar('\n');

	return 0;
}