简体   繁体   English

如何在选择排序算法中利用另一种方法中的方法?

[英]How to make use of the methods in another method in selection sort algorithm?

this is to swap这是交换

public class SelectionSort {

    private static void swap(int[] f, int idx1, int idx2) {
        int tmp = f[idx1];
        f[idx1]=f[idx2];
        f[idx2]=tmp;
    }

return the index of largest element in array f, from0 to upTo.返回数组 f 中最大元素的索引,从 0 到 upTo。 but here i have mistake..idx1 can not be identified?但这里我有错误..idx1 无法识别?

    private static int getIndexOfGreatestElement(int[] f, int upTo) {

        int max_idx = idx1;
        for (int idx2 = idx1 -1; idx2 >=0; idx2--)
            if (f[idx2] > f[max_idx])
                max_idx = idx2;

how to implement the selectionSort and getIndexOfGreatestElement in this method?如何在此方法中实现 selectionSort 和 getIndexOfGreatestElement?


    public static void sort(int[] f) {

        for (idx1=upTo-1; idx1 >0 ; idx1--)
        { .swap().getindexofgresterelement
    }




I made a few small changes in your code and made use of all the methods:我对您的代码进行了一些小改动,并使用了所有方法:

public static void sort(int[] f) {
    int max_idx;
    for (int idx1 = 0; idx1 < f.length - 1; idx1++) {
        max_idx = getIndexOfGreatestElement(f, idx1);
        swap(f, idx1, max_idx);
    }
}

private static int getIndexOfGreatestElement(int[] f, int upTo) {

    int max_idx = upTo;
    for (int idx2 = upTo; idx2 < f.length; idx2++)
        if (f[idx2] > f[max_idx])
            max_idx = idx2;
    return max_idx;
}

private static void swap(int[] f, int idx1, int idx2) {
    int tmp = f[idx1];
    f[idx1] = f[idx2];
    f[idx2] = tmp;
}

public static void main(String[] args) {
    int[] arr = {5, 8, 2, 1, 14, 7, 10, 33};
    sort(arr);
    System.out.println(Arrays.toString(arr));
}

Although, this works and will sort the array in Descending order, I think the method getIndexOfGreatestElement, should be removed (in my opinion it overcomplicated the code and makes it harder to understand).虽然这可行并且会按降序对数组进行排序,但我认为应该删除 getIndexOfGreatestElement方法(在我看来,它使代码过于复杂并且更难理解)。

How I would write Selection Sort (ascending order):我将如何编写选择排序(升序):

public class Selection_Sort {

  public void  sort( int[] array) {

      for (var i = 0; i < array.length - 1; i++) {
          var minIndex = i; 
          for (var j = i; j < array.length; j++)  
              if (array[j] < array[minIndex])
                  minIndex = j;
          swap(array, minIndex, i);
      }
  }

  private void swap(int[] array, int index1, int index2) {
      var temp = array[index1];
      array[index1] = array[index2];
      array[index2] = temp;
  }}

class test {
  public static void main(String[] args) {
      int[] arr = {5, 8, 2, 1, 14, 7, 10, 33};
      var selectionObj = new Selection_Sort();
      selectionObj.sort(arr);
      System.out.println(Arrays.toString(arr));
  }}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM