java - Something Wrong with QuickSort algorithm -


quick sort java implementation- have made program implement quicksort algorithm, not showing sorted sequence properly, showing array out of bound index exception. can tell wrong code or logic?

import java.util.*;  public class quicksort{     int num,arrayqs[],i;      public void quicksort(int ar[],int start,int end){         if(start<end){             int pindex=partition(ar,start,end);             system.out.println(pindex);             quicksort(ar,start,pindex-1);             quicksort(ar,pindex+1,end);         }     }     public int partition(int par[],int start, int end){ //partition function          int key;         int swapper;         int pivot=par[end];         int pindex=start;         for(i=0;i<end;i++){             if(par[i]<=pivot){                 //swapiing                 key=par[pindex];                 par[pindex]=par[i];                 par[i]=key;                 pindex++;             }         }         //swap         swapper=par[pindex];         par[pindex]=par[end];         par[end]=swapper;         return pindex;     }     public void arrayinputfn(){         scanner in=new scanner(system.in);         system.out.println("enter number want insert in array");         num=in.nextint();         arrayqs=new int[num];         system.out.println("enter elements in array: ");         for(i=0;i<num;i++){             arrayqs[i]=in.nextint();         }         quicksort(arrayqs,0,arrayqs.length-1);          for(i=0;i<arrayqs.length;i++){             system.out.print(arrayqs[i]);         }     }     public static void main(string[] args){         quicksort qs=new quicksort();         qs.arrayinputfn();     } } 

for(i=0;i<end;i++){ beginning index should start, not 0. passing entire array method sort part of @ once (other first call), specified start , end.

you should extract swap method make code neater.

public int partition(int par[], int start, int end) {     int pivot = par[end];     int pindex = start;     (i = start; < end; i++) {         if (par[i] <= pivot) {             swap(par, i, pindex);             pindex++;         }     }     swap(par, pindex, end);     return pindex; }  public void swap(int[] arr, int a, int b) {     int temp = arr[a];     arr[a] = arr[b];     arr[b] = temp; } 

Comments

Popular posts from this blog

sublimetext3 - what keyboard shortcut is to comment/uncomment for this script tag in sublime -

java - No use of nillable="0" in SOAP Webservice -

ubuntu - Laravel 5.2 quickstart guide gives Not Found Error -