Java常用排序算法+程序員必須掌握的8大排序算法+二分法查找法


本文由網絡資料整理轉載而來,如有問題,歡迎指正!

分類:

1)插入排序(直接插入排序、希爾排序)

2)交換排序(冒泡排序、快速排序)

3)選擇排序(直接選擇排序、堆排序)

4)歸並排序

5)分配排序(基數排序)

所需輔助空間最多:歸並排序

所需輔助空間最少:堆排序

平均速度最快:快速排序

不穩定:快速排序,希爾排序,堆排序。

先來看看 8種排序之間的關系:

1.直接插入排序

1)基本思想:在要排序的一組數中,假設前面(n-1)[n>=2] 個數已經是排

 

好順序的,現在要把第n 個數插到前面的有序數中,使得這 n個數

也是排好順序的。如此反復循環,直到全部排好順序。

2)實例

3)用java實現

 

[java] view plaincopy

1. package com.njue;

2.

3. publicclass insertSort {

4.

5. public insertSort(){

6. inta[]={49,38,65,97,76,13,27,49,78,34,12,64,5,4,62,99,98,54,56,17,18,23,

34,15,35,25,53,51};

7. int temp=0;

8. for(int i=1;i<a.length;i++){

9. int j=i-1;

10. temp=a[i];

11. for(;j>=0&&temp<a[j];j--){

12. a[j+1]=a[j]; //將大於temp 的值整體后移一個單位

13. }

14. a[j+1]=temp;

15. }

16.

17. for(int i=0;i<a.length;i++){

18. System.out.println(a[i]);

19. }

20. }

2. 希爾排序(最小增量排序)

 

1)基本思想:算法先將要排序的一組數按某個增量 dn/2,n為要排序數的個數)分成若

干組,每組中記錄的下標相差 d.對每組中全部元素進行直接插入排序,然后再用一個較小

的增量(d/2)對它進行分組,在每組中再進行直接插入排序。當增量減到 1 時,進行直接

插入排序后,排序完成。

2)實例:

3)用java實現

[java] view plaincopy

1. publicclass shellSort {

2.

3. publicshellSort(){

4.

5. int a[]={1,54,6,3,78,34,12,45,56,100};

6. double d1=a.length;

7. int temp=0;

8.

9. while(true){

10. d1= Math.ceil(d1/2);

11. int d=(int) d1;

12. for(int x=0;x<d;x++){

13.

14. for(int i=x+d;i<a.length;i+=d){

15. int j=i-d;

16. temp=a[i];

17. for(;j>=0&&temp<a[j];j-=d){

18. a[j+d]=a[j];

19. }

20. a[j+d]=temp;

21. }

22. }

 

23.

24. if(d==1){

25. break;

26. }

27.

28. for(int i=0;i<a.length;i++){

29. System.out.println(a[i]);

30. }

31. }

3.簡單選擇排序

1)基本思想:在要排序的一組數中,選出最小的一個數與第一個位置的數交換;

然后在剩下的數當中再找最小的與第二個位置的數交換,如此循環到倒數第二個數和最后一

個數比較為止。

2)實例:

3)用java實現

[java] view plaincopy

1. publicclass selectSort {

2.

3. public selectSort(){

4. int a[]={1,54,6,3,78,34,12,45};

5. int position=0;

6. for(int i=0;i<a.length;i++){

7. int j=i+1;

8. position=i;

9. int temp=a[i];

10. for(;j<a.length;j++){

11. if(a[j]<temp){

12. temp=a[j];

13. position=j;

14. }

 

15. }

16. a[position]=a[i];

17. a[i]=temp;

18. }

19.

20. for(int i=0;i<a.length;i++)

21. System.out.println(a[i]);

22. }

23. }

4, 堆排序

1)基本思想:堆排序是一種樹形選擇排序,是對直接選擇排序的有效改進。

堆的定義如下:具有n個元素的序列(h1,h2,...,hn),當且僅當滿足(hi>=h2i,hi>=2i+1)或

hi<=h2i,hi<=2i+1(i=1,2,...,n/2)時稱之為堆。在這里只討論滿足前者條件的堆。由堆的

定義可以看出,堆頂元素(即第一個元素)必為最大項(大頂堆)。完全二叉樹可以很直觀

地表示堆的結構。堆頂為根,其它為左子樹、右子樹。初始時把要排序的數的序列看作是一

棵順序存儲的二叉樹,調整它們的存儲序,使之成為一個堆,這時堆的根節點的數最大。然

后將根節點與堆的最后一個節點交換。然后對前面(n-1)個數重新調整使之成為堆。依此類

推,直到只有兩個節點的堆,並對它們作交換,最后得到有 n個節點的有序序列。從算法

描述來看,堆排序需要兩個過程,一是建立堆,二是堆頂與堆的最后一個元素交換位置。所

以堆排序有兩個函數組成。一是建堆的滲透函數,二是反復調用滲透函數實現排序的函數。

(2)實例:

初始序列:46,79,56,38,40,84

建堆:

交換,從堆中踢出最大數

剩余結點再建堆,再交換踢出最大數

依次類推:最后堆中剩余的最后兩個結點交換,踢出一個,排序完成。

3)用java實現

[java] view plaincopy

1. import java.util.Arrays;

2.

3. publicclass HeapSort {

4. inta[]={49,38,65,97,76,13,27,49,78,34,12,64,5,4,62,99,98,54,56,17,18,23,

34,15,35,25,53,51};

5. public HeapSort(){

6. heapSort(a);

7. }

8.

9. public void heapSort(int[] a){

10. System.out.println("開始排序");

11. int arrayLength=a.length;

12. //循環建堆

 

13. for(int i=0;i<arrayLength-1;i++){

14. //建堆

15. buildMaxHeap(a,arrayLength-1-i);

16. //交換堆頂和最后一個元素

17. swap(a,0,arrayLength-1-i);

18. System.out.println(Arrays.toString(a));

19. }

20. }

21.

22.

23.

24. private void swap(int[] data, int i, int j) {

25. // TODO Auto-generated method stub

26. int tmp=data[i];

27. data[i]=data[j];

28. data[j]=tmp;

29. }

30.

31. //data 數組從0lastIndex 建大頂堆

32. privatevoid buildMaxHeap(int[] data, int lastIndex) {

33. // TODO Auto-generated method stub

34. //lastIndex 處節點(最后一個節點)的父節點開始

35.

36. for(int i=(lastIndex-1)/2;i>=0;i--){

37. //k 保存正在判斷的節點

38. int k=i;

39. //如果當前k節點的子節點存在

40. while(k*2+1<=lastIndex){

41. //k 節點的左子節點的索引

42. int biggerIndex=2*k+1;

43. //如果biggerIndex 小於lastIndex,即biggerIndex+1 代表的k 節點的

右子節點存在

44. if(biggerIndex<lastIndex){

45. //若果右子節點的值較大

46. if(data[biggerIndex]<data[biggerIndex+1]){

47. //biggerIndex 總是記錄較大子節點的索引

48. biggerIndex++;

49. }

50. }

51.

52. //如果k節點的值小於其較大的子節點的值

53. if(data[k]<data[biggerIndex]){

54. //交換他們

55. swap(data,k,biggerIndex);

 

56. //biggerIndex 賦予k,開始while 循環的下一次循環,重新保證k

節點的值大於其左右子節點的值

57. k=biggerIndex;

58. }else{

59. break;

60. }

61. }

62. }

63. }

64. }

5.冒泡排序

1)基本思想:在要排序的一組數中,對當前還未排好序的范圍內的全部數,自上而下對

相鄰的兩個數依次進行比較和調整,讓較大的數往下沉,較小的往上冒。即:每當兩相鄰的

數比較后發現它們的排序與排序要求相反時,就將它們互換。

2)實例:

3)用java實現

[java] view plaincopy

1. publicclass bubbleSort {

2.

3. publicbubbleSort(){

4. inta[]={49,38,65,97,76,13,27,49,78,34,12,64,5,4,62,99,98,54,56,17,18,23

,34,15,35,25,53,51};

5. int temp=0;

6. for(int i=0;i<a.length-1;i++){

7. for(int j=0;j<a.length-1-i;j++){

8. if(a[j]>a[j+1]){

9. temp=a[j];

 

10. a[j]=a[j+1];

11. a[j+1]=temp;

12. }

13. }

14. }

15.

16. for(int i=0;i<a.length;i++){

17. System.out.println(a[i]);

18. }

19. }

 

 

 

6.快速排序

1)基本思想:選擇一個基准元素,通常選擇第一個元素或者最后一個元素,通過一趟掃描,

將待排序列分成兩部分,一部分比基准元素小,一部分大於等於基准元素,此時基准元素在其

排好序后的正確位置,然后再用同樣的方法遞歸地排序划分的兩部分。

2)實例:

3)用java實現

 

[java] view plaincopy

 

1. publicclass quickSort {

2.

3. inta[]={49,38,65,97,76,13,27,49,78,34,12,64,5,4,62,99,98,54,56,17,18,23,34

,15,35,25,53,51};

4. publicquickSort(){

5. quick(a);

6. for(int i=0;i<a.length;i++){

7. System.out.println(a[i]);

8. }

9. }

10. publicint getMiddle(int[] list, int low, int high) {

11. int tmp =list[low]; //數組的第一個作為中軸

12. while (low < high){

13. while (low < high&& list[high] >= tmp) {

14. high--;

15. }

16.

17. list[low] =list[high]; //比中軸小的記錄移到低端

18. while (low < high&& list[low] <= tmp) {

19. low++;

20. }

21.

22. list[high] =list[low]; //比中軸大的記錄移到高端

23. }

24. list[low] = tmp; //中軸記錄到尾

25. return low; //返回中軸的位置

26. }

27.

28. publicvoid _quickSort(int[] list, int low, int high) {

29. if (low < high){

30. int middle =getMiddle(list, low, high); //list 數組進行一分

為二

31. _quickSort(list, low, middle - 1); //對低字表進行遞歸排

32. _quickSort(list,middle + 1, high); //對高字表進行遞歸排

33. }

34. }

35.

36. publicvoid quick(int[] a2) {

37. if (a2.length > 0) { //查看數組是否為空

38. _quickSort(a2,0, a2.length - 1);

39. }

40. }

 

41. }

 

 

7、歸並排序

 

1)基本排序:歸並(Merge)排序法是將兩個(或兩個以上)有序表合並成一個新的有

序表,即把待排序序列分為若干個子序列,每個子序列是有序的。然后再把有序子序列合並

為整體有序序列。

2)實例:

3)用java實現

[java] view plaincopy

1. import java.util.Arrays;

2.

3. publicclass mergingSort {

4.

5. inta[]={49,38,65,97,76,13,27,49,78,34,12,64,5,4,62,99,98,54,56,17,18,23,34,1

5,35,25,53,51};

6.

7. publicmergingSort(){

8. sort(a,0,a.length-1);

9. for(int i=0;i<a.length;i++)

10. System.out.println(a[i]);

11. }

12.

13. publicvoid sort(int[] data, int left, int right) {

14. // TODO Auto-generatedmethod stub

15. if(left<right){

16. //找出中間索引

17. int center=(left+right)/2;

18. //對左邊數組進行遞歸

 

19. sort(data,left,center);

20. //對右邊數組進行遞歸

21. sort(data,center+1,right);

22. //合並

23. merge(data,left,center,right);

24. }

25.

26. }

27.

28. publicvoid merge(int[] data, int left, int center, int right) {

29. // TODO Auto-generatedmethod stub

30. int [] tmpArr=newint[data.length];

31. int mid=center+1;

32. //third 記錄中間數組的索引

33. int third=left;

34. int tmp=left;

35. while(left<=center&&mid<=right){

36. //從兩個數組中取出最小的放入中間數組

37. if(data[left]<=data[mid]){

38. tmpArr[third++]=data[left++];

39. }else{

40. tmpArr[third++]=data[mid++];

41. }

42.

43. }

44.

45. //剩余部分依次放入中間數組

46. while(mid<=right){

47. tmpArr[third++]=data[mid++];

48. }

49.

50. while(left<=center){

51. tmpArr[third++]=data[left++];

52. }

53.

54. //將中間數組中的內容復制回原數組

55. while(tmp<=right){

56. data[tmp]=tmpArr[tmp++];

57. }

58. System.out.println(Arrays.toString(data));

59. }

60. }

8、基數排序

 

1)基本思想:將所有待比較數值(正整數)統一為同樣的數位長度,數位較短的數前面

補零。然后,從最低位開始,依次進行一次排序。這樣從最低位排序一直到最高位排序完成

以后,數列就變成一個有序序列。

2)實例:

3)用java實現

[java] view plaincopy

1. import java.util.ArrayList;

2. import java.util.List;

3.

4. public class radixSort {

5. inta[]={49,38,65,97,76,13,27,49,78,34,12,64,5,4,62,99,98,54,101,56,17,18

,23,34,15,35,25,53,51};

6. public radixSort(){

7. sort(a);

8. for(inti=0;i<a.length;i++){

9. System.out.println(a[i]);

 

10. }

11. }

12. public void sort(int[] array){

13. //首先確定排序的趟數;

14. int max=array[0];

15. for(inti=1;i<array.length;i++){

16. if(array[i]>max){

17. max=array[i];

18. }

19. }

20. int time=0;

21. //判斷位數;

22. while(max>0){

23. max/=10;

24. time++;

25. }

26.

27. //建立10個隊列;

28. List<ArrayList> queue=newArrayList<ArrayList>();

29. for(int i=0;i<10;i++){

30. ArrayList<Integer>queue1=new ArrayList<Integer>();

31. queue.add(queue1);

32. }

33.

34. //進行time 次分配和收集;

35. for(int i=0;i<time;i++){

36. //分配數組元素;

37. for(intj=0;j<array.length;j++){

38. //得到數字的第time+1 位數;

39. int x=array[j]%(int)Math.pow(10,i+1)/(int)Math.pow(10, i);

 

40. ArrayList<Integer>queue2=queue.get(x);

41. queue2.add(array[j]);

42. queue.set(x, queue2);

43. }

44. int count=0;//元素計數器;

45. //收集隊列元素;

46. for(int k=0;k<10;k++){

47. while(queue.get(k).size()>0){

48. ArrayList<Integer>queue3=queue.get(k);

49. array[count]=queue3.get(0);

50. queue3.remove(0);

51. count++;

52. }

 

53. }

54. }

55. }

56. }

 

 

 

 

import java.io.*;

 

public class Paixu {

// 冒泡排序法

public void Maopao(int a[]) {

for (int i = 1; i < a.length; i++) {

for (int j = 0; j < a.length - i; j++) {

if (a[j] > a[j + 1]) {

int temp = a[j + 1];

a[j + 1] = a[j];

a[j] = temp;

}

}

}

System.out.println("\n" + "采用冒泡排序法:");

}

 

// 插入排序法:

public void Charu(int a[]) {

for (int i = 1; i < a.length; i++) {

for (int j = 0; j < i; j++) {

if (a[j] > a[i]) {

int temp = a[i];

for (int k = i; k > j; k--) {

a[k] = a[k--];

}

a[j] = temp;

}

}

}

System.out.println("\n" + "采用插入排序法:");

}

 

// 選擇排序法:

public void Xuanze(int a[]) {

for (int i = 0; i < a.length; i++) {

int position = i;

for (int j = i + 1; j < a.length; j++) {

if (a[position] > a[j]) {

int temp = a[position];

a[position] = a[j];

a[j] = temp;

}

}

}

System.out.println("\n" + "采用選擇排序法:");

}

 

public void Print(int a[]) {

System.out.println("從小到大排序結果為:");

for (int i = 0; i < a.length; i++) {

System.out.print(a[i] + ",");

}

}

 

public static void main(String[] args) {

int a[] = new int[5];

Paixu px = new Paixu();

BufferedReader buf = new BufferedReader(

new InputStreamReader(System.in));

System.out.println("請輸入五個整數:");

for (int i = 0; i < a.length; i++) {

try {

String s = buf.readLine();

int j = Integer.parseInt(s);

a[i] = j;

} catch (Exception e) {

System.out.println("出錯了!必須輸入整數,請重新輸入!");

i--;

}

}

System.out.println("您輸入的整數依次為:");

for (int i = 0; i < a.length; i++) {

System.out.print(a[i] + ",");

}

System.out.println("\n" + "-------------");

px.Maopao(a); // 調用冒泡算法

px.Print(a);

System.out.println("\n" + "-------------");

px.Charu(a); // 調用插入算法

px.Print(a);

System.out.println("\n" + "-------------");

px.Xuanze(a); // 調用選擇算法

px.Print(a);

}

}

 

 

Java實現二分查找

現在復習下

import java.util.*;

public class BinarySearch {

public static void main(String[] args) {
ArrayList<Integer> a = new ArrayList<Integer>();
addIntegerInSequence(a,1,10);
print(a);
int pos = binarySearch(a,10);
if ( pos != -1 )
{
System.out.print("Element found: " + pos);
}
else
{
System.out.print("Element not found");
}
}

/**
* 二分查找法
* @param a
* @param value 待查找元素
* @return
*/
public static int binarySearch(ArrayList<Integer> a, int value)
{
int size = a.size();
int low = 0 , high = size - 1;
int mid;
while (low <= high)
{
mid = (low + high) / 2;
if ( a.get(mid) < value )
{
low = low + 1;
}
else if ( a.get(mid) > value )
{
high = high - 1;
}
else
{
return mid;
}
}
return -1;
}

/**
* 填充順序元素到數組
* @param a
* @param begin 開始元素
* @param size 大小
*/
public static void addIntegerInSequence(ArrayList<Integer> a, int begin, int size)
{
for (int i = begin; i < begin + size; i++)
{
a.add(i);
}
}

/**
* 打印數組
* @param a
*/
public static void print(ArrayList<Integer> a)
{
Iterator<Integer> i = a.iterator();
while (i.hasNext())
{
System.out.print(i.next() + " ");
}
System.out.println("");
}

}

 

/////

JAVA 庫中的二分查找使用非遞歸方式實現,返回結果與前面寫的有所不同:找不到時返回的是負數,但不一定是-1

private static int binarySearch0(int[] a, int fromIndex, int toIndex,

int key) {

int low = fromIndex;

int high = toIndex - 1;

 

while (low <= high) {

int mid = (low + high) >>> 1;

int midVal = a[mid];

 

if (midVal < key)

low = mid + 1;

else if (midVal > key)

high = mid - 1;

else

return mid; // key found

}

return -(low + 1); // key not found.

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM