Java的冒泡排序和快速排序.

冒泡排序算法的运作如下:
1、比较相邻的元素。如果第一个比第二个大,就交换他们两个。
2、对每一对相邻元素作同样的工作,从开始第一对到结尾的最后一对。在这一点,最后的元素应该会是最大的数。
3、针对所有的元素重复以上的步骤,除了最后一个。
4、持续每次对越来越少的元素重复上面的步骤,直到没有任何一对数字需要比较。

冒泡排序最好的时间复杂度为0(n)
冒泡排序最坏的时间复杂度为0(n2) //n的平方
因此冒泡排序总的平均时间复杂度为0(n2)

冒泡排序是就地排序,且它是稳定的。

 

[java]  view plain  copy
  1. public class Test {  
  2.   
  3.     public static void main(String[] args) {  
  4.         int temp[] = {13,52,3,8,5,16,41,29};  
  5.         //执行temp.length次  
  6.         for (int i = 0; i < temp.length; i++) {  
  7.             for (int j = 0; j < temp.length-i-1; j++) {  
  8.                 if(temp[j]>temp[j+1]){ //前一个数和后一个数比较  
  9.                     int a = temp[j];  
  10.                     temp[j] = temp[j+1];  
  11.                     temp[j+1] = a;  
  12.                 }  
  13.             }  
  14.         }  
  15.         for (int i = 0; i < temp.length; i++) {  
  16.             System.out.print(temp[i]+" ");  
  17.         }  
  18.     }  
  19. }  


 

快速排序(Quicksort)是对冒泡排序的一种改进。它的基本思想是:通过一趟排序将要排序的

数据分割成独立的两部分,其中一部分的所有数据都比另外一部分的所有数据都要小,然后再

按此方法对这两部分数据分别进行快速排序,整个排序过程可以递归进行,以此达到整个数据

变成有序序列

 

快速排序不是一种稳定的排序算法

扫描二维码关注公众号,回复: 1686269 查看本文章
时间复杂度为o(n2)。
 
[java]  view plain  copy
  1. package com.itmyhome;  
  2.   
  3. import java.util.Arrays;  
  4. public class T {  
  5.     public static void main(String[] ary) {  
  6.         int[] arry = { 49386597761327 };  
  7.         sort(arry, 0, arry.length - 1);  
  8.     }  
  9.   
  10.     private static int sortUnit(int[] array, int low, int high) {  
  11.         int key = array[low];  
  12.         while (low < high) {  
  13.             while (array[high] >= key && high > low)  
  14.                 --high;  
  15.             array[low] = array[high];  
  16.             while (array[low] <= key && high > low)  
  17.                 ++low;  
  18.             array[high] = array[low];  
  19.         }  
  20.         array[high] = key;  
  21.         System.out.println(Arrays.toString(array));  
  22.         return high;  
  23.     }  
  24.   
  25.     public static void sort(int[] array, int low, int high) {  
  26.         if (low >= high)  
  27.             return;  
  28.         int index = sortUnit(array, low, high);  
  29.         sort(array, low, index - 1);  
  30.         sort(array, index + 1, high);  
  31.     }  
  32. }  

猜你喜欢

转载自blog.csdn.net/qq_18972767/article/details/78488715