sample sorting code.

hi all,

is that code below, efficient or fast enough for large amount of data and is it a quicksort algorithm?

if it's a quicksort algorithm how can i randomly select the pivot data? can i use rnd() function to select randomly pivot data from the array?

sorry for my poor english and thanks in advance

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
#include <stdio.h>
void sort(int array[], int size) {
	int count_gt = 0;
	int count_ls = 0;
	int count_eq = 0;
	int count = 0;
	
	if(size > 1) {
		int temp_gt[size-1];
		int temp_ls[size-1];
		int temp_eq[size-1];
		for(int i=0; i < size; i++) {
			if(array[0] < array[i]) temp_gt[count_gt++] = array[i];
			if(array[0] > array[i]) temp_ls[count_ls++]  = array[i];
			if(array[0] == array[i]) temp_eq[count_eq++] = array[i];
		}
	
		for(count=0; count < count_ls; count++) array[count] = temp_ls[count];
		for(int cnt = 0; cnt < count_eq; cnt++) array[count++] = temp_eq[cnt];
		for(int cnt = 0; cnt < count_gt; cnt++) array[count+cnt] = temp_gt[cnt];

		sort(&array[0], count_ls);
		sort(&array[count], count_gt);
	}
}
	
int main() {
	
	int d[] = {8, 8, 1, 1, 4, 4, 9, 6, 7, 0, 0, 21, 3, 12, 0, 19, 19};
	int size = sizeof d / sizeof (int);
	sort(d, size);
	
	for(int i=0; i < size; i++) printf(" %d ",d[i]);
	printf("\n");

	return 0;
}

Last edited on
Maybe you should benchmark your code against what I wrote below. Replace std::array with std::vector, remove the ", 17" and include <vector> and it'll work as well.

Also your code is more C-like than C++. I think we don't use stdio.h or *.h any more, instead it's cstdio and cstdlib and cmath...


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <algorithm>
#include <array>


int main()
{
    std::array<int, 17> items
    {8, 8, 1, 1, 4, 4, 9, 6, 7, 0, 0, 21, 3, 12, 0, 19, 19};

    std::sort(items.begin(), items.end());

    for (int i = 0; i < items.size(); ++i)
        std::cout << items[i] << std::endl;

    return 0;
}
Topic archived. No new replies allowed.