| do inplace sorting of arrays i... | |||||||
|
30 Day Risk-Free Guarantee:
100% money back if you're unsatisfied. Book (308 Pages):
![]() Video (One Hour):
![]() Resume Review (24 - 48hr)
All Products / Services
|
|||||||
@snehal do u mind writing code
public class QuickSort {
public static void main(String[] args) {
int[] a = new int[]{5,3,2,6,4,1,3,7};
quicksort(a, 0, a.length-1);
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + " ");
}
}
public static void quicksort(int[] a, int left, int right){
if(left < 0 || right >= a.length)
return;
if(right <= left)
return;
int endValue = a[right];//Choose the last element as the partition element
int partitionIndex = partition(a, endValue, left, right-1);//Partition the array
if(a[partitionIndex] < endValue){
++partitionIndex;
}
swap(a, partitionIndex, right);
quicksort(a, left, partitionIndex-1);
quicksort(a, partitionIndex+1, right);
}
public static int partition(int a[], int endValue,int left,int right){
while(left < right){
if(a[left] < endValue){
left++;
continue;
}
if(a[right] >= endValue){
right--;
continue;
}
swap(a, left, right);
++left;
--right;
}
return left;
}
public static void swap(int[] a, int left, int right){
int temp = a[left];
a[left] = a[right];
a[right] = temp;
}
}
worst case for quick sort is O(n^2)...
so pass through the array once and find the median and then do the quick sort..
running time is O(n) + O(nlogn) = O(nlogn).. correct me if am wrong
@clrs
How to find median in O(n)?
@andy
use SELECT(k) algorithm that returns the k'th biggest number.. here we need n/2th biggest number. Can some one tell me if select algorithm is O(n) or O(n log n)?
I remember reading it is O(n)..
@clrs
Can u post the code/logic for SELECT(k) algorithm?
Another in place sorting method which takes O(nlogn) time is heapsort. It is slower than quicksort but it has the advantage that its worst case time is also O(nlogn)
if Shellsort is inplace then it takes only O(n^1.5)
Heap sort - it's inplace and O(nlog n)
Quicksort - O(nlgn)