Java implements recursive and non-recursive quicksort

Recursive pit digging

void quicksort(int s[],int left,int right){
        if(left<right){
            int temp,i=left,j=right;
            temp=s[right];
            while(i<j){
                //find the first subscript on the left that is greater than the base value
                while(s[i]<=temp&&i<j)i++;
                if(i<j)s[j--]=s[i];
                //find the first subscript on the right that is less than the base value
                while(s[j]>=temp&&i<j)j--;
                if(i<j)s[i++]=s[j];
            }
            s[i]=temp;
            quicksort(s,left,i-1); //recursive left part of the array
            quicksort(s,i+1,right); //Recursive right part of the array
        }
    }

 Non-recursive (using LinkedHashMap)

void quickSort1(int s[],int left,int right){
        LinkedHashMap<Integer,Integer> lhp=new LinkedHashMap<>();
        //Put 0,n into LinkedHashMap
        lhp.put(left,right);
        while(!lhp.isEmpty()){ //As long as there are segments that need to be sorted
            //read left, right
            Iterator<Map.Entry<Integer,Integer>> it=lhp.entrySet().iterator();
            left=it.next().getKey();
            right=lhp.get(left);
            // and remove from LinkedHashMap
            lhp.remove(left,right);
            if(left>=right)continue;
            int i=left,j=right,temp=s[right];
            while(i<j){ //traverse and sort again
                while(s[i]<=temp&&i<j)i++;
                if(i<j)s[j--]=s[i];
                while(s[j]>=temp&&i<j)j--;
                if(i<j)s[i++]=s[j];
            }
            s[i]=temp;
            lhp.put(left,i-1);
            lhp.put(i+1,right);
        }
    }

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324738316&siteId=291194637