修改java中的代码

时间:2012-09-10 16:10:44

标签: java sorting

所以我写了一些相当标准的排序算法来排序字符串数组。我想修改一些排序方法,以便他们对数据进行略微不同的排序。这就是我想要做的事情:

选择排序当前运行数组的剩余部分,查找最小值,然后将其交换到前面。我想更改算法,以便它在剩余部分中查找最大值,并将其交换到后面,以便它同时从前面和后面构建一个排序列表。

插入排序当前将每个项目插入从左侧构建的已排序区域。它通过向下搜索已排序的区域,一次一个项目来完成此操作。我想在该区域使用二分搜索来找到插入项目的正确位置。

这是我到目前为止的代码:

/** 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;
    }
} 

0 个答案:

没有答案