I'm trying to make the quicksort but it's not working at all.
I made a helper function "swap" so I can call it back in the "quick"function. then used recursive method to do it till the array is sorted.

The problem is.. IT'S CRASHING EVERYTIME I RUN IT... i think i'm calling it wrong in the main() ..... any ideas?... =)

int swap (int mark1, int mark2)
{
    int temp;

    temp = mark1;
    mark1 = mark2;
    mark2 = temp;
}

void quick (int Array[], int left, int right)  // make helper function called swap
{
     int pivot = Array[(left+right)/2];

     while(left <= right)
     {
        while(Array[left] < pivot)
            left++;
        while(Array[right] > pivot)
            right--;
        if(left <= right)
        {
            swap(Array[left], Array[right]);
            left++;
            right--;
        }
     }

     if(pivot-left > 1)
        quick(Array,left,pivot-1);
     if (pivot + right > 1)
        quick(Array,right,pivot+1);
}
int main()
{
	int Array[100];
	int chosen;
	do
	{
		system("CLS");
		cout << "Welcome to the Searching and Sorting Engine!" << endl;
		cout << "\n0. Exit." << endl;
		cout << "1. Use Quick sort." << endl;
		cout << "Please choose an item: ";
		cin  >> chosen;

	         if (chosen ==1)
		{
			quick (Array, 0, 100);
			system("PAUSE");
		}

	}while (chosen > 0 && chosen <= 1);

	system("PAUSE");
	return EXIT_SUCCESS;
}

I think you have at least two problems:

  • Your array is 100 (uninitialised) elements (numbered from 0 to 99), but you pass in left = 0 and right = 100 , then on line 18, you do while(Array[right] > pivot) , which is guaranteed to try and access Array[100] on the first iteration - not allowed!
  • Your swap() function does not do what you think it does. You're passing the arguments by value, so your function swaps local copies of the values, but those in the calling function are not affected. I would change swap() to:
    // Function now returns 'void' and the arguments are passed by reference
    void swap (int& mark1, int& mark2)
    {
        int temp(mark1);   // Use initialisation-is-assignment for slightly better efficiency
        mark1 = mark2;
        mark2 = temp;
    }
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.