码迷,mamicode.com
首页 > 其他好文 > 详细

冒泡,快排代码+注释

时间:2016-09-11 22:51:33      阅读:126      评论:0      收藏:0      [点我收藏+]

标签:

冒泡:

package Sort;

public class BubbleSort {
    public static void main(String[] args) {
        int[] list = new int[]{12,14,3,24,1,33};
        int[] nums = bubbleSort(list);
        for(int i = 0;i< list.length;i++){
            System.out.println(nums[i]);
        }
    }
    
    public static int[] bubbleSort(int[] nums){
        int n = nums.length;
        for(int i= 0;i<n;i++){
            for(int j= i+1;j<n-i-1;j++){
                int temp = nums[i];
                nums[i] = nums[j];
                nums[j] = temp;
             }
        }
        return nums;
    }
}

快排:

package Sort;

public class QuickSort {

    public static void main(String[] args) {
        int[] unsortedList = new int[] { 49, 38, 65, 97, 76, 13, 27, 49 };
        quickSort(unsortedList, 0, 7);
        for (int i = 0; i < unsortedList.length; i++) {
            System.out.println(unsortedList[i]);
        }
    }

    public static void quickSort(int[] unsortedList, int low, int high) {
        if (low < high) {// 只有一个元素时,退出
            int k = partition(unsortedList, low, high);
            quickSort(unsortedList, low, k - 1);
            quickSort(unsortedList, k + 1, high);
        }
    }

    /**
     * nums进行一次以pivot为界限的分割
     * 
     * @param nums
     * @param low
     * @param high
     * @return
     */
    public static int partition(int[] nums, int low, int high) {
        // 定义pivot,存储pivot,定义low high
        if (low == high)
            return low;
        int pivot = nums[low];
        // low==high时,停止本趟partition
        while (low < high) {
            // 定义low,high,从high开始寻找比pivot小的数,放进坑里
            while (low < high && nums[high] >= pivot)
                high--;
            nums[low] = nums[high];
            // 从low开始寻找比pivot大的数,放进坑里
            while (low < high && nums[low] <= pivot)
                low++;
            nums[high] = nums[low];
        }
        nums[low] = pivot;
        return low;
    }

}

 

冒泡,快排代码+注释

标签:

原文地址:http://www.cnblogs.com/jinxialiu/p/5862909.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!