<pre id="bbfd9"><del id="bbfd9"><dfn id="bbfd9"></dfn></del></pre>

          <ruby id="bbfd9"></ruby><p id="bbfd9"><mark id="bbfd9"></mark></p>

          <p id="bbfd9"></p>

          <p id="bbfd9"><cite id="bbfd9"></cite></p>

            <th id="bbfd9"><form id="bbfd9"><dl id="bbfd9"></dl></form></th>

            <p id="bbfd9"><cite id="bbfd9"></cite></p><p id="bbfd9"></p>
            <p id="bbfd9"><cite id="bbfd9"><progress id="bbfd9"></progress></cite></p>
            java語言

            java常見的排序算法的代碼

            時間:2025-03-26 13:40:07 java語言 我要投稿
            • 相關推薦

            java常見的排序算法的代碼

              穩定度(穩定性)

              一個排序算法是穩定的,就是當有兩個相等記錄的關鍵字R和S,且在原本的列表中R出現在S之前,在排序過的列表中R也將會是在S之前。

              排序算法分類

              常見的有插入(插入排序/希爾排序)、交換(冒泡排序/快速排序)、選擇(選擇排序)、合并(歸并排序)等。

              一.插入排序

              插入排序(Insertion Sort),它的工作原理是通過構建有序序列,對于未排序數據,在已排序序列中從后向前掃描,找到相應位置并插入。插入排序在實現上,通常采用in-place排序(即只需用到O(1)的額外空間的排序),因而在從后向前掃描過程中,需要反復把已排序元素逐步向后挪位,為最新元素提供插入空間。

              一般來說,插入排序都采用in-place在數組上實現。具體算法描述如下:從第一個元素開始,該元素可以認為已經被排序。取出下一個元素,在已經排序的元素序列中從后向前掃描。如果該元素(已排序)大于新元素,將該元素移到下一位置。重復步驟3,直到找到已排序的元素小于或者等于新元素的位置。將新元素插入到該位置后。重復步驟2~5。

              復制代碼 代碼如下:

              public static void ionSort(int[] data) {

              for (int index = 1; index < data.length; index++) {

              int key = data[index];

              int position = index;

              // shift larger values to the right

              while (position > 0 && data[position - 1] > key) {

              data[position] = data[position - 1];

              position--;

              }

              data[position] = key;

              }

              }

              二.希爾排序

              希爾排序(Shell Sort)是插入排序的一種。是針對直接插入排序算法的改進。該方法又稱縮小增量排序,因DL.Shell于1959年提出而得名。

              希爾排序是基于插入排序的以下兩點性質而提出改進方法的:插入排序在對幾乎已經排好序的數據操作時, 效率高, 即可以達到線性排序的效率。但插入排序一般來說是低效的, 因為插入排序每次只能將數據移動一位。

              復制代碼 代碼如下:

              staticvoid shellSort(Lista) {

              int h = 1;

              while (h < a.size()/3) h = h*3 + 1; //: 1, 4, 13, 40, 121, ...

              for (; h >= 1; h /= 3)

              for (int i = h; i < a.size(); i++)

              for (int j = i; j >= h && a.get(j).compareTo(a.get(j-h)) < 0; j-=h)

              Collections.swap(a, j, j-h);

              }

              三.冒泡排序

              冒泡排序(Bubble Sort,臺灣譯為:泡沫排序或氣泡排序)是一種簡單的排序算法。它重復地走訪過要排序的數列,一次比較兩個元素,如果他們的順序錯誤就把他們交換過來。走訪數列的工作是重復地進行直到沒有再需要交換,也就是說該數列已經排序完成。這個算法的名字由來是因為越小的元素會經由交換慢慢“浮”到數列的頂端。

              冒泡排序算法的運作如下:

              比較相鄰的元素,如果第一個比第二個大,就交換他們兩個。

              對每一對相鄰元素作同樣的工作,從開始第一對到結尾的最后一對,在這一點,最后的元素應該會是最大的數。

              針對所有的元素重復以上的步驟,除了最后一個。

              持續每次對越來越少的元素重復上面的步驟,直到沒有任何一對數字需要比較。

              復制代碼 代碼如下:

              public static void bubbleSort(int[] data) {

              int temp = 0;

              for (int i = data.length - 1; i > 0; --i) {

              boolean isSort = false;

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

              if (data[j + 1] < data[j]) {

              temp = data[j];

              data[j] = data[j + 1];

              data[j + 1] = temp;

              isSort = true;

              }

              }

              // 如果一次內循環中發生了交換,那么繼續比較;如果一次內循環中沒發生任何交換,則認為已經排序好了。

              if (!isSort)

              break;

              }

              }

              四.快速排序

              快速排序(Quicksort)是對冒泡排序的一種改進。由C. A. R. Hoare在1962年提出。它的基本思想是:通過一趟排序將要排序的數據分割成獨立的兩部分,其中一部分的所有數據都比另外一部分的所有數據都要小,然后再按此方法對這兩部分數據分別進行快速排序,整個排序過程可以遞歸進行,以此達到整個數據變成有序序列。

              快速排序使用分治法(Divide and conquer)策略來把一個串行(list)分為兩個子串行(sub-lists)。

              步驟為:

              從數列中挑出一個元素,稱為 "基準"(pivot)。重新排序數列,所有元素比基準值小的擺放在基準前面,所有元素比基準值大的擺在基準的后面(相同的數可以到任一邊)。在這個分區退出之后,該基準就處于數列的中間位置。這個稱為分區(partition)操作。遞歸地(recursive)把小于基準值元素的子數列和大于基準值元素的子數列排序。

              復制代碼 代碼如下:

              /*

              * more efficient implements for quicksort.

              * use left, center and right median value (@see #median()) for the pivot, and

              * the more efficient inner loop for the core of the algorithm.

              */

              public class Quicksort {

              public static final int CUTOFF = 11;

              /**

              * quick sort algorithm.

              *

              * @param arr an array of Comparable items.

              */

              public staticvoid quicksort(T[] arr) {

              quickSort(arr, 0, arr.length - 1);

              }

              /**

              * get the median of the left, center and right.

              * order these and hide the pivot by put it the end of of the array.

              *

              * @param arr an array of Comparable items.

              * @param left the most-left index of the subarray.

              * @param right the most-right index of the subarray.

              * @return T

              */

              public staticT median(T[] arr, int left, int right) {

              int center = (left + right) / 2;

              if (arr[left].compareTo(arr[center]) > 0)

              swapRef(arr, left, center);

              if (arr[left].compareTo(arr[right]) > 0)

              swapRef(arr, left, right);

              if (arr[center].compareTo(arr[right]) > 0)

              swapRef(arr, center, right);

              swapRef(arr, center, right - 1);

              return arr[right - 1];

              }

              /**

              * internal method to sort the array with quick sort algorithm.

              *

              * @param arr an array of Comparable Items.

              * @param left the left-most index of the subarray.

              * @param right the right-most index of the subarray.

              */

              private staticvoid quickSort(T[] arr, int left, int right) {

              if (left + CUTOFF <= right) {

              // find the pivot

              T pivot = median(arr, left, right);

              // start partitioning

              int i = left, j = right - 1;

              for (;;) {

              while (arr[++i].compareTo(pivot) < 0);

              while (arr[--j].compareTo(pivot) > 0);

              if (i < j)

              swapRef(arr, i, j);

              else

              break;

              }

              // swap the pivot reference back to the small collection.

              swapRef(arr, i, right - 1);

              quickSort(arr, left, i - 1); // sort the small collection.

              quickSort(arr, i + 1, right); // sort the large collection.

              } else {

              // if the total number is less than CUTOFF we use ion sort

              // instead (cause it much more efficient).

              ionSort(arr, left, right);

              }

              }

              /**

              * method to swap references in an array.

              *

              * @param arr an array of Objects.

              * @param idx1 the index of the first element.

              * @param idx2 the index of the second element.

              */

              public staticvoid swapRef(T[] arr, int idx1, int idx2) {

              T tmp = arr[idx1];

              arr[idx1] = arr[idx2];

              arr[idx2] = tmp;

              }

              /**

              * method to sort an subarray from start to end with ion sort

              * algorithm.

              *

              * @param arr an array of Comparable items.

              * @param start the begining position.

              * @param end the end position.

              */

              public staticvoid ionSort(T[] arr, int start, int end) {

              int i;

              for (int j = start + 1; j <= end; j++) {

              T tmp = arr[j];

              for (i = j; i > start && tmp.compareTo(arr[i - 1]) < 0; i--) {

              arr[i] = arr[i - 1];

              }

              arr[i] = tmp;

              }

              }

              private static void printArray(Integer[] c) {

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

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

              System.out.println();

              }

              public static void main(String[] args) {

              Integer[] data = {10, 4, 9, 23, 1, 45, 27, 5, 2};

              System.out.println("bubbleSort...");

              printArray(data);

              quicksort(data);

              printArray(data);

              }

              }

              五.選擇排序

              選擇排序(Selection sort)是一種簡單直觀的排序算法。它的工作原理如下。首先在未排序序列中找到最小(大)元素,存放到排序序列的起始位置,然后,再從剩余未排序元素中繼續尋找最小(大)元素,然后放到已排序序列的末尾。以此類推,直到所有元素均排序完畢。

              因為每一趟確定元素的過程中都會有一個選擇最小值的子流程,所以人們形象地稱之為選擇排序。

              舉個例子,序列5 8 5 2 9,我們知道第一遍選擇第1個元素5會和2交換,那么原序列中2個5的相對前后順序就被破壞了,所以選擇排序不是一個穩定的排序算法。

              復制代碼 代碼如下:

              public static void selectSort(int[] data) {

              int minIndex = 0;

              int temp = 0;

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

              minIndex = i; // 無序區的最小數據數組下標

              for (int j = i + 1; j < data.length; j++) { // 在無序區中找到最小數據并保存其數組下標

              if (data[j] < data[minIndex]) {

              minIndex = j;

              }

              }

              if (minIndex != i) { // 如果不是無序區的最小值位置不是默認的第一個數據,則交換之。

              temp = data[i];

              data[i] = data[minIndex];

              data[minIndex] = temp;

              }

              }

              }

              六.歸并排序

              歸并排序(Merge sort)是建立在歸并操作上的一種有效的排序算法。該算法是采用分治法(Divide and Conquer)的一個非常典型的應用。

              歸并操作的過程如下:

              申請空間,使其大小為兩個已經排序序列之和,該空間用來存放合并后的序列。

              設定兩個指針,最初位置分別為兩個已經排序序列的起始位置。

              比較兩個指針所指向的元素,選擇相對小的元素放入到合并空間,并移動指針到下一位置。

              重復步驟3直到某一指針達到序列尾。

              將另一序列剩下的所有元素直接復制到合并序列尾。

              復制代碼 代碼如下:

              public static int[] mergeSort(int[] arr) {// 歸并排序 --遞歸

              if (arr.length == 1) {

              return arr;

              }

              int half = arr.length / 2;

              int[] arr1 = new int[half];

              int[] arr2 = new int[arr.length - half];

              System.arraycopy(arr, 0, arr1, 0, arr1.length);

              System.arraycopy(arr, half, arr2, 0, arr2.length);

              arr1 = mergeSort(arr1);

              arr2 = mergeSort(arr2);

              return mergeSortSub(arr1, arr2);

              }

              private static int[] mergeSortSub(int[] arr1, int[] arr2) {// 歸并排序子程序

              int[] result = new int[arr1.length + arr2.length];

              int i = 0;

              int j = 0;

              int k = 0;

              while (true) {

              if (arr1[i] < arr2[j]) {

              result[k] = arr1[i];

              if (++i > arr1.length - 1) {

              break;

              }

              } else {

              result[k] = arr2[j];

              if (++j > arr2.length - 1) {

              break;

              }

              }

              k++;

              }

              for (; i < arr1.length; i++) {

              result[++k] = arr1[i];

              }

              for (; j < arr2.length; j++) {

              result[++k] = arr2[j];

              }

              return result;

              }

              完整代碼(除QuickSort)

              復制代碼 代碼如下:

              package com.clzhang.sample.thinking;

              import java.util.*;

              /**

              * 幾路常見的排序算法Java實現

              * @author acer

              *

              */

              public class CommonSort {

              /**

              * 插入排序具體算法描述如下:

              * 1.從第一個元素開始,該元素可以認為已經被排序

              * 2.取出下一個元素,在已經排序的元素序列中從后向前掃描

              * 3.如果該元素(已排序)大于新元素,將該元素移到下一位置

              * 4.重復步驟3,直到找到已排序的元素小于或者等于新元素的位置

              * 5.將新元素插入到該位置后

              * 6.重復步驟2~5

              */

              public static void ionSort(int[] data) {

              for (int index = 1; index < data.length; index++) {

              int key = data[index];

              int position = index;

              // shift larger values to the right

              while (position > 0 && data[position - 1] > key) {

              data[position] = data[position - 1];

              position--;

              }

              data[position] = key;

              }

              }

              /**

              * 希爾排序,算法實現思想參考維基百科;適合大數量排序操作。

              */

              staticvoid shellSort(Lista) {

              int h = 1;

              while (h < a.size()/3) h = h*3 + 1; //: 1, 4, 13, 40, 121, ...

              for (; h >= 1; h /= 3)

              for (int i = h; i < a.size(); i++)

              for (int j = i; j >= h && a.get(j).compareTo(a.get(j-h)) < 0; j-=h)

              Collections.swap(a, j, j-h);

              }

              /**

              * 冒泡排序算法的運作如下:

              * 1.比較相鄰的元素。如果第一個比第二個大,就交換他們兩個。

              * 2.對每一對相鄰元素作同樣的工作,從開始第一對到結尾的最后一對。在這一點,最后的元素應該會是最大的數。

              * 3.針對所有的元素重復以上的步驟,除了最后一個。

              * 4.持續每次對越來越少的元素重復上面的步驟,直到沒有任何一對數字需要比較。[1]

              */

              public static void bubbleSort(int[] data) {

              int temp = 0;

              for (int i = data.length - 1; i > 0; --i) {

              boolean isSort = false;

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

              if (data[j + 1] < data[j]) {

              temp = data[j];

              data[j] = data[j + 1];

              data[j + 1] = temp;

              isSort = true;

              }

              }

              // 如果一次內循環中發生了交換,那么繼續比較;如果一次內循環中沒發生任何交換,則認為已經排序好了。

              if (!isSort)

              break;

              }

              }

              /**

              * 選擇排序的基本思想是:

              * 1.遍歷數組的過程中,以 i 代表當前需要排序的序號,則需要在剩余的 [i+1…n-1] 中找出其中的最小值,

              * 2.然后將找到的最小值與 i 指向的值進行交換。

              * 因為每一趟確定元素的過程中都會有一個選擇最小值的子流程,所以人們形象地稱之為選擇排序。

              * @param data

              */

              public static void selectSort(int[] data) {

              int minIndex = 0;

              int temp = 0;

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

              minIndex = i; // 無序區的最小數據數組下標

              for (int j = i + 1; j < data.length; j++) { // 在無序區中找到最小數據并保存其數組下標

              if (data[j] < data[minIndex]) {

              minIndex = j;

              }

              }

              if (minIndex != i) { // 如果不是無序區的最小值位置不是默認的第一個數據,則交換之。

              temp = data[i];

              data[i] = data[minIndex];

              data[minIndex] = temp;

              }

              }

              }

              /**

              * 歸并操作的過程如下:

              * 1.申請空間,使其大小為兩個已經排序序列之和,該空間用來存放合并后的序列

              * 2.設定兩個指針,最初位置分別為兩個已經排序序列的起始位置

              * 3.比較兩個指針所指向的元素,選擇相對小的元素放入到合并空間,并移動指針到下一位置

              * 4.重復步驟3直到某一指針達到序列尾

              * 5.將另一序列剩下的所有元素直接復制到合并序列尾

              */

              public static int[] mergeSort(int[] arr) {// 歸并排序 --遞歸

              if (arr.length == 1) {

              return arr;

              }

              int half = arr.length / 2;

              int[] arr1 = new int[half];

              int[] arr2 = new int[arr.length - half];

              System.arraycopy(arr, 0, arr1, 0, arr1.length);

              System.arraycopy(arr, half, arr2, 0, arr2.length);

              arr1 = mergeSort(arr1);

              arr2 = mergeSort(arr2);

              return mergeSortSub(arr1, arr2);

              }

              private static int[] mergeSortSub(int[] arr1, int[] arr2) {// 歸并排序子程序

              int[] result = new int[arr1.length + arr2.length];

              int i = 0;

              int j = 0;

              int k = 0;

              while (true) {

              if (arr1[i] < arr2[j]) {

              result[k] = arr1[i];

              if (++i > arr1.length - 1) {

              break;

              }

              } else {

              result[k] = arr2[j];

              if (++j > arr2.length - 1) {

              break;

              }

              }

              k++;

              }

              for (; i < arr1.length; i++) {

              result[++k] = arr1[i];

              }

              for (; j < arr2.length; j++) {

              result[++k] = arr2[j];

              }

              return result;

              }

              private static void printArray(int[] c) {

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

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

              System.out.println();

              }

              public static void main(String []args){

              int[] data = {10,4,9,23,1,45,27,5,2};

              System.out.println("bubbleSort...");

              int[] a = data.clone();

              printArray(a);

              bubbleSort(a);

              printArray(a);

              System.out.println("selectSort...");

              int[] b = data.clone();

              printArray(b);

              selectSort(b);

              printArray(b);

              System.out.println("ionSort...");

              int[] c = data.clone();

              printArray(c);

              ionSort(c);

              printArray(c);

              System.out.println("shellSort...");

              Listlist = new ArrayList();

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

              list.add(data[i]);

              System.out.println(list);

              shellSort(list);

              System.out.println(list);

              System.out.println("mergeSort...");

              int[] d = data.clone();

              printArray(d);

              printArray(mergeSort(d));

              }

              }

            【java常見的排序算法的代碼】相關文章:

            JAVA語言的常見排序算法07-16

            Java排序算法06-17

            冒泡排序算法原理及JAVA實現代碼方法10-16

            C語言快速排序算法及代碼06-25

            常用Java排序算法詳解09-17

            java堆排序的算法思想的分析09-14

            java的常見排序方法08-31

            C語言奇偶排序算法詳解及實例代碼10-30

            C語言選擇排序算法及實例代碼07-25

                    <pre id="bbfd9"><del id="bbfd9"><dfn id="bbfd9"></dfn></del></pre>

                    <ruby id="bbfd9"></ruby><p id="bbfd9"><mark id="bbfd9"></mark></p>

                    <p id="bbfd9"></p>

                    <p id="bbfd9"><cite id="bbfd9"></cite></p>

                      <th id="bbfd9"><form id="bbfd9"><dl id="bbfd9"></dl></form></th>

                      <p id="bbfd9"><cite id="bbfd9"></cite></p><p id="bbfd9"></p>
                      <p id="bbfd9"><cite id="bbfd9"><progress id="bbfd9"></progress></cite></p>
                      飘沙影院