1

そのため、文字列の配列をソートするためのかなり標準的なソート アルゴリズムをいくつか作成しました。いくつかの並べ替え方法を変更して、データの並べ替え方法を少し変えたいと思いました。これが私がやりたかったことです:

Selection Sort は現在、配列の残りの部分を実行し、最小値を探してから、それを先頭にスワップします。アルゴリズムを変更して、残りの部分の最大値も探し、それを後ろにスワップして、前と後ろから同時にソートされたリストを作成するようにします。

挿入ソートは現在、左から構築しているソート済み領域に各項目を挿入します。これは、ソートされた領域を一度に 1 項目ずつ検索することによって行われます。その領域でバイナリ検索を使用して、アイテムを挿入する適切な場所を見つけたかったのです。

これは私がこれまで持っているコードです:

/** Swaps the specified elements of an array.
 *  Used in several of the sorting algorithms
 */
private  void swap(String[ ] data, int here, int there){
    String temp = data[here];
    data[here] = data[there];
    data[there] = temp;
}

/* ===============SELECTION SORT================= */

/** Sorts the elements of an array of String using selection sort */
public  void selectionSort(String[ ] data){
    // for each position, from 0 up, find the next smallest item 
    // and swap it into place
    for (int place=0; place<data.length-1; place++){
        int minIndex = place;
        for (int sweep=place+1; sweep<data.length; sweep++){
            if (data[sweep].compareTo(data[minIndex]) < 0)
                minIndex=sweep;
        }
        swap(data, place, minIndex);
    }
}

/* ===============INSERTION SORT================= */
/** Sorts the  elements of an array of String using insertion sort */
public  void insertionSort(String[] data){
    // for each item, from 0, insert into place in the sorted region (0..i-1)
    for (int i=1; i<data.length; i++){
        String item = data[i];
        int place = i;
        while (place > 0  &&  item.compareTo(data[place-1]) < 0){
            data[place] = data[place-1];       // move up
            place--;
        }
        data[place]= item;
    }
} 
4

0 に答える 0