Error with quick_sort algorithm

Today, I have coded using quick-sort algorithm. But it caused an error on my computer. Can somebody help me fix the code.
#include<iostream>
#include<fstream>
#include<vector>
#include<conio.h>
#include<cstdlib>

using namespace std;

int n;
vector<int> a(100);

void input(void){
	ifstream f("input.txt");
	
	if(!f){
		cout<<"\n Tep khong ton tai";
	getch();
	exit(1);
	}
	f>>n;
	int i;
	for(i=0;i<n;i++)
		f>>a[i];	
	f.close();
}

void quicksort(int L, int H)
{
	int X = (L + H)/2;
	int i = L;
	int j = H;
	int tmp;
	while(i <= j)
	{
		while( a[i] <= a[X]) i++;
		while( a[j] >= a[X]) j--;
		if(i <= j)
		{
			tmp = a[i];
			a[i] = a[j];
			a[j] = tmp;	
			i++;
			j--;
		}
	}
	if(i < H) quicksort( i, H);
	if(L < j) quicksort( L, j);
}

void output(char *filename){
	ofstream f;
	f.open(filename);
	int i;
	for( i = 0; i < n; i++)
		f<<a[i];
}


int main()
{
	input();
	quicksort(0, n-1);
	int i; 
	for(i = 0; i < n; i++)
	cout<<a[i]<<"	";
	output("out.txt");
}
Last edited on
You should also mention the error that you are getting.

One problem seems to be in your inner while loops. If a [X] is the smallest or the largest number in the array then one of these loops will keep looping till it goes out of range and causes segmentation fault.

You have to provide additional termination conditions to these loops.
Last edited on
Thank you. My error is *.exe has stop working. I have known how to fix it. This must be written that:
while( a[i] < a[X]) i++;
while( a[j] > a[X]) j--;
Topic archived. No new replies allowed.