Hello I've recently started testing out QuickSort. I've written a program that makes array with the size of user's input and fills it with random numbers, then it uses quicksort to sort it. Now here is my problem. On linux machine with just 4gb of RAM I could make array with a size up to 10^8 before computer would become unusable. On my mac with 8gb of RAM I can only make an array with a size up to 10^6. If I try making an array with size of 10^7 and greater I get segmentation fault. Is it some hard restriction from operating system, can it be changed? Here is my code :
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int FindPivot(int i, int j);
void PrintTable(int* table, int size);
void NextThing(int* table, int size);
void QuickSort(int* table, int i, int j);
void RandomizeTable (int* table, int size) {
int i;
for (i = 0; i < size; i++) {
table[i] = -10000 + rand() % (10000+1-(-10000));
//printf("%d\t", table[i]);
}
printf("\n");
NextThing(table, size);
}
void NextThing(int* table, int size) {
printf("Sorting the table...\n");
clock_t x = clock();
QuickSort(table, 0, size - 1);
clock_t y= clock();
printf("Time it took : %fs\n", ((double)(y - x))/CLOCKS_PER_SEC);
//Second sorting of the table, just to see how long does it take for quicksort to sort an already sorted table
printf("Sorting the table...\n");
clock_t x2 = clock();
QuickSort(table, 0, size - 1);
clock_t y2= clock();
printf("Time it took : %fs\n", ((double)(y2 - x2))/CLOCKS_PER_SEC);
exit(0);
}
void Swap(int* table, int i, int j) {
int temp;
temp = table[i];
table[i] = table[j];
table[j] = temp;
}
int Partition(int* table, int i, int j) {
int p, q, key;
p = FindPivot(i, j);
key = table[p];
Swap(table, i, p);
for (p = i, q = i + 1; q <= j; q++)
if (table[q] < key) {
p++;
Swap(table, p, q);
}
Swap(table, i, p);
return p;
}
void QuickSort(int* table, int i, int j) {
int p;
if (i < j) {
p = Partition(table, i, j);
QuickSort(table, i, p - 1);
QuickSort(table, p + 1, j);
}
}//QuickSort
void PrintTable(int* table, int size) {
int i;
for (i = 0; i < size; i++)
printf("%d", table[i]);
printf("\n");
}
int FindPivot(int i, int j) {
int pivot;
/*pivot = i + rand() % (j + 1 - i); */ //Method I randomizing pivot
pivot = (i + j) / 2; //Method II arithmetic avarage
return pivot;
}
int main () {
time_t t;
srand((unsigned) time(&t));
int n;
printf("Array size:");
scanf("%d", &n);
int tab[n]; //Here is where error occurs if array size is > 10^6
RandomizeTable(tab, n);
}
I am almost sure it's problem with making an array of such size. I've tried debugging the code with a printf. It printed text if it was before making an array (in main()) and wouldn't print it if I put it afterwards.