java非遞歸方式實現快速排序

Java非遞歸方式實現快速排序
java

package sort.algorithm;
import java.util.Stack;
//快速排序的非遞歸實現,利用系統的棧stack
public class QuickSortNonRecursion {
     public static void main(String[] args) { 
         QuickSortNonRecursion qsnr = new QuickSortNonRecursion(); 
         int[] array = {0, 2, 11, 121, 18, 99, 3, 5, 101, 22, 9, 100}; 
         qsnr.quicksort(array); 
          for (int i : array) { 
                System.out.print(i + "  "); 
          } 
        } 
                
        public void quicksort(int[] array) { 
            if (array == null || array.length == 1) return; 
            //存放開始與結束索引
            Stack<Integer> s = new Stack<Integer>();  
            //壓棧        
            s.push(0);  
            s.push(array.length - 1);  
            //利用循環裏實現
            while (!s.empty()) {  
                int right = s.pop();  
                int left = s.pop();  
                //若是最大索引小於等於左邊索引,說明結束了
                if (right <= left) continue;  
                        
                int i = partition(array, left, right);  
                if (left < i - 1) { 
                    s.push(left); 
                    s.push(i - 1); 
                }  
                if (i + 1 < right) { 
                    s.push(i+1); 
                    s.push(right); 
                } 
            }  
        } 
        //找到軸心,進行交換 
        public int partition (int[] data, int first, int end)
        { 
            int temp;
            int i=first,j=end;
            if(first<end)
            {
                temp=data[i];
                //當i=j的時候,則說明掃描完成了
                while(i<j)
                {
                    //從右邊向左邊掃描找到一個小於temp的元素
                    while(j>i&&data[j]>temp)j--;
                    if(i<j)
                    {
                        //將該元素賦值給temp
                        data[i]=data[j];
                        //賦值後就應該將i+1指向下一個序號
                        i++;
                    }
                          
                    //而後從左邊向右邊開始掃描,找到一個大於temp的元素
                    while(i<j&&temp>data[i])i++;
                    if(i<j)
                    {
                        //將該元素賦值給temp
                        data[j]=data[i];
                        //賦值後就應該將j-1指向前一個序號
                        j--;
                    }
                }
                //將軸數據放在i位置中
                data[i]=temp;
            }
            return i;
        } 
    }
相關文章
相關標籤/搜索