Showing posts with label Sorting. Show all posts
Showing posts with label Sorting. Show all posts

Tuesday, December 13, 2011

Heap Sort



public class HeapSort {

public static void main(String[] args) {
int a[] = {1,2,3,4,5,6,7,8,9,11,10,13,12,11,10};
heapsort(a);
       for(int b :a)
      System.out.println(b);
}

public static void heapsort(int[] a){
int temp;
int currRoot = 0;
buildmaxHeap(a);
int heapSize = a.length-1;
for(int i = a.length-1;i>0;i--) {
temp = a[i];
a[i] = a[0];
a[0] = temp;
heapSize--;
maxHeapify(a,currRoot,heapSize);
}

}

public static void buildmaxHeap(int[] a){
for(int i = (int) Math.ceil((a.length-1)/2); i>=0;i--)
maxHeapify(a,i,a.length-1);
}


public static void maxHeapify(int[] a,int currRootIndex,int heapSize) {
int largest,temp;
int  leftIndex = 2* currRootIndex + 1;
int rightIndex = 2* currRootIndex + 2;
if(leftIndex <= heapSize && a[leftIndex] > a[currRootIndex])
largest = leftIndex;
else
largest = currRootIndex;
if(rightIndex <= heapSize && a[rightIndex] > a[largest])
largest = rightIndex;
if(largest != currRootIndex){
temp = a[currRootIndex];
a[currRootIndex] = a[largest];
a[largest] = temp;
maxHeapify(a, largest, heapSize);
}
}
}


Monday, December 12, 2011

Quick Sort


public class Quick {

  public static void main(String[] args) {
 
     int[] a = {3,2,5,1,7,8,10};
     quick(a,0,a.length-1);
     for(int b : a)
        System.out.println(b);
  }

  public static int partition(int[] a, int p, int q){
    int pivot = a[p];
    int temp;
    int i = p;
    for(int j = p+1;j<a.length;j++) {
       if(a[j]<=pivot){
         temp=a[i+1];
         a[i+1]=a[j];
         a[j] = temp;
         i++;
       }
    }
    temp = a[i];
    a[i] = a[p];
    a[p]=temp;
    return i;
  }

  public static void quick(int[] a, int p, int q) {
    if(p<q) {
      int r = partition(a,p,q);
      quick(a,p,r-1);
      quick(a,r+1,q);
    }
  }

  }

Insertion Sort


public static int[] insertion(int[] a){
int key;
for(int j=1;j<a.length;j++ ) {
key=a[j];
  int i=j-1;
while(i >= 0 && a[i] > key){
a[i+1] = a[i];
i--;
}
a[i+1] = key;
}
return a;
}