算法题——Sort Colors(JAVA)快排

题目描述:
Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue.

Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.

读题:
给定一个数组上来就排序啊

知识储备:
快速排序

最好时间最坏时间平均时间空间复杂度稳定性
O(nlog2n)(以2为底)O(n^2)O(nlog2n)O(log2n)不稳定

一、分解:本质上快速排序把数据划分成几份,所以快速排序通过选取一个关键数据,再根据它的大小,把原数组分成两个子数组:第一个数组里的数都比这个主元数据小或等于,而另一个数组里的数都比这个主元数据要大或等于。

≤xx≥x

二、解决:用递归来处理两个子数组的排序。 (也就是说,递归地求上面图示中左半部分,以及递归地求上面图示中右半部分。)

三、合并:因为子数组都是原址排序,所以不需要合并操作,通过上面两步后数组已经排好序了。

解题思路:
直接用快速排序解决。

提交代码:

public class Solution {

    private int one = 0;
    private int flag = 0;
    public void sortColors(int[] nums) {
        if (nums != null) {
            //
            int[] arr = new int[nums.length+1];
            arr[0] = 1;
            arraycopy(nums, 0, arr, int 1, int nums.length);
            sort(nums, 0, arr.length-1);
        }
    }
    public void sort(int[] a,int low,int high){
         int i = low;
         int j = high;
         int key = a[low];


         while (j > i){
             //从后往前比较
             while( j > i && a[j] >= key)  //如果没有比关键值小的,比较下一个,直到有比关键值小的交换位置,然后又从前往后比较
                 j--;
             if (a[j] <= key){
                 int temp = a[j];
                 a[j] = a[i];
                 a[i] = temp;
                 if (flag == 0) { 
                    one = j;
                 }
             }
             //从前往后比较
             while (j > i && a[i] <= key)//如果没有比关键值大的,比较下一个,直到有比关键值大的交换位置
                i++;
             if (a[i] >= key){
                 int temp = a[i];
                 a[i] = a[j];
                 a[j] = temp;
             }
         //此时第一次循环比较结束,关键值的位置已经确定了。左边的值都比关键值小,右边的值都比关键值大,但是两边的顺序还有可能是不一样的,进行下面的递归调用
         }
         //递归
         if (i > low) sort(a,low,i-1);//左边序列。第一个索引位置到关键值索引-1
         if (j < high) sort(a,j+1,high);//右边序列。从关键值索引+1到最后一个
     }
}
点赞