The average case time complexity for a quick sort algorithm is O(nlogn).That means it should be strictly increasing with increasing value of n. But why the time is increasing-decreasing-increasing in this case. Why is it decreasing with increasing value of n
I am generating random inputs using the function of java
What will be the solution for this??
public class Qsort {
static Scanner sc = new Scanner(System.in);
public static void main(String args[]) throws IOException {
File file = new File("Qtest.txt");
PrintWriter output = new PrintWriter(file);
int n,i;
System.out.println("Enter the times of iteration");
n = sc.nextInt();
for(int j=1000;j<=n*1000;j=j+1000)
{
Random r = new Random();
int array[];
array = new int[j];
for(i=0;i<j;i++)
{
array[i] = r.nextInt(2000);
}
long startTime = System.nanoTime();
Qsort(array,0,j-1);
long endTime = System.nanoTime();
output.println(j + " " + (endTime-startTime));
System.out.println("After sorting the time elapsed is " +(endTime-startTime));
}
output.close();
}
The sort function for Quick Sort
public static void Qsort(int A[],int start,int end)
{
if(start>=end) return;
int p = partition(A,start,end);
Qsort(A,start,p-1);
Qsort(A,p+1,end);
}
public static int partition(int A[],int start,int end)
{
int pivot = A[end];
int p = start;
for(int i =start;i<end;i++)
{
if(A[i]<=pivot)
{
int temp = A[i];
A[i] = A[p];
A[p] = temp;
p++;
}
}
int temp = A[p];
A[p] = A[end];
A[end] = temp;
return p;
}
}
The output that I am getting:
Enter the times of iteration 10
For 1000 inputs : After sorting the time elapsed is 779133
For 2000 inputs : After sorting the time elapsed is 8350639
For 3000 inputs : After sorting the time elapsed is 607856
For 4000 inputs : After sorting the time elapsed is 833593
For 5000 inputs : After sorting the time elapsed is 1042426
For 6000 inputs : After sorting the time elapsed is 1283195
For 7000 inputs : After sorting the time elapsed is 1497488
For 8000 inputs : After sorting the time elapsed is 1261182
For 9000 inputs : After sorting the time elapsed is 1207128
For 10000 inputs : After sorting the time elapsed is 1427456