Javaソート------交換ソート



Java Sort Exchange Sort



アルゴリズムの最も基本的なものはソートです。今日は、Javaで交換ソートをソートして記録します。

ここでの並べ替え方法は小さいものから大きいものへと変化し、大きいものから小さいものへと実際に記号が変化します。



スワップソートを実装するには、次の2つの方法があります。
1つ、バブルソート
2、クイックソート

以下の内容は純粋に個人的な理解です。何か問題がある場合は、コメントして修正してください。



最初にバブルソートについて話しましょう:

1つ、バブルソート

バブルソートは、その名前が示すように、水底から小さなものから大きなものへと上昇する泡のようなものです(水圧の問題)。
並べ替えの過程で、あなたはしなければなりません サイクル 最小値を一番上に置くと、次のことがわかります。
1.1回のバブリングが通過します 常にポジションを入れ替える シーケンス内の最小値を一番上に並べ替えます
2.次のバブリングは最後の位置から始まります
3.このようにして、n-k個の要素がk番目のバブルに対してトラバースされます。
4.合計n-1サイクルのバブリング。

コード
public void bubbleSort(int[] elements){ int length = elements.length for (int j = length j > 1 j--) { //Use the outer loop to control the number of elements sorted each time for (int i = 1 i // Use the inner cycle to complete the sorting of the elements if (elements[i] 1]){ int temp = elements[i - 1] elements[i - 1] = elements[i] elements[i] = temp } } } }

2、クイックソート

クイックソート、**デュアルポインタ**メソッドを使用して、①最初に右ポインタを**ベース**よりも小さい値に移動し、次に値を左ポインタが指す要素に移動してトラバーサルを停止します。次に、②左ポインタがベースより大きい値にトラバースし、次に右ポインタが指す要素に値を移動し、トラバースを停止します。2つのポインタが一致するまで操作①②を繰り返し、ポインタとベースが指す要素を交換します。ポインタが指す位置は、シーケンスを左右の2つのシーケンスに分割し、各シーケンスは上記のすべての手順を繰り返します。 >ダブルポインタ:実際、要素の位置を記録する2つの変数があります。 >カーディナリティー:通常、シーケンスの最初の値は、右ポインターからの移動を決定します。これは、左ポインターと右ポインターが重なるときに、ポイントされる要素がベースよりも小さいことを確認する必要があるためです。
コード
public void quickSort(int[] elements, int left, int right){ if (left >= right){ //The left and right pointers coincide return } int pivotPos = partition(elements, left, right)//Move the left and right pointer quickSort(elements, left, pivotPos - 1) // Repeat the above steps in the left sequence quickSort(elements, pivotPos + 1, right) // Repeat the above steps in the right sequence } private int partition(int[] elements, int left, int right) { int pivotKey = elements[left] // Get the base, the first element of the sequence while (left // Whether the left and right pointers coincide while (left = pivotKey) //Whether the value pointed to by the right pointer is greater than the base right-- elements[left] = elements[right] // Move the element pointed to by the right pointer to the element pointed to by the left pointer while (left //Whether the value pointed to by the left pointer is smaller than the base left++ elements[right] = elements[left] //Move the element pointed to by the left pointer to the element pointed to by the right pointer } elements[left] = pivotKey // Move the base to the position where the left and right pointers coincide return left //Return to the position where the left and right pointers coincide }