Java选择排序修改

时间:2015-12-14 04:58:08

标签: java sorting selection

所以我做了这个选择排序代码,但我想让它在每次调用函数时增加一个排序循环。

所以我觉得没问题。为什么不删除外部for循环并将index替换为顶部的静态变量,并在每次函数完成其操作时递增它。但这真的很糟糕。有人可以帮忙吗?

问题:每次调用此函数时,如何一次一步地进行排序?

我不希望它一次性整理所有东西

private static void selectionSort(int[] array) {
    for (int index = 0; index < array.length; index++) {
        int currentMin = array[index];
        int indexOfMin = index;

        for(int j = index+1; j < array.length; j++) {
            if(array[j] < currentMin) { 
                currentMin = array[j];
                indexOfMin = j;
            }
        }
        swap(array, index, indexOfMin);
    }
}

private static void swap(int[] a, int i, int j) {
    int temp = a[i];
    a[i] = a[j];
    a[j] = temp;
}

3 个答案:

答案 0 :(得分:1)

为什么全局变量不能完成这项工作?你想发布你的解决方案,我们可以看看吗?或者您也可以将起始索引传递给函数,并在每次按下按钮时使用增量索引调用它。

for (int fromIndex = 0; fromIndex < array.length; fromIndex++) {
    // Stop here and wait for button click.
    selectionSort(fromIndex, array);
}

然后在main中,将其称为:

{{1}}

答案 1 :(得分:0)

通话功能

import java.util.Comparator;

import tg.cw.pd.model.ModelcurrentMin;

public class SortData implements Comparator<Object>
{
    public int compare(Object o1, Object o2) 
    {

        int result;

        String desc1 = ((ModelcurrentMin)o1).getcurrentMin();
        String desc2 = ((ModelcurrentMin)o2).getcurrentMin();

        result = desc1.compareTo(desc2);    //asc
        return   result;
   }
}
SortData.java中的

NSURLSessionDownloadTask

答案 2 :(得分:0)

检查一下..

public static void main(String[] args) {
    int[] array = new int[]{3, 4, 2, 7, 1, 5, 6};
    System.out.println(Arrays.toString(array));   //[2, 4, 3, 7, 5, 1, 6]

    selectionSort(array);                         
    System.out.println(Arrays.toString(array));   //[1, 4, 3, 7, 5, 2, 6]

    selectionSort(array);                         
    System.out.println(Arrays.toString(array));   //[1, 2, 3, 7, 5, 4, 6]

    selectionSort(array);                        
    System.out.println(Arrays.toString(array));   //[1, 2, 3, 4, 5, 7, 6]

    selectionSort(array);                      
    System.out.println(Arrays.toString(array));   //[1, 2, 3, 4, 5, 6, 7]
}

private static void selectionSort(int[] array) {
    for (int index = 0; index < array.length; index++) {
        int currentMin = array[index];
        int indexOfMin = index;
        boolean swapNeeded = false;

        for (int j = index + 1; j < array.length; j++) {
            if (array[j] < currentMin) {
                currentMin = array[j];
                indexOfMin = j;
                swapNeeded = true;
            }
        }
        if (swapNeeded) {
            swap(array, index, indexOfMin);
            return;
        }
    }
}

private static void swap(int[] a, int i, int j) {
    int temp = a[i];
    a[i] = a[j];
    a[j] = temp;
}

selectionSort()必须被调用7次才能对此数组进行排序。

但是如果你考虑像{3, 5, 1, 4, 7, 6, 2}这样的数组,3 rd 和4 rd 数组的索引已经在排序的位置。因此,selectionSort()必须只被调用5次。