簡體   English   中英

在 j 處遞增,即使它不滿足條件

[英]Incrementing at j even though it doesn't meet the condition

你好有人可以幫我嗎?

public class sorting{
   
  public static void sort(int arr[])
    {
        int n = arr.length;
        int count = 0;
        int tempArr [] = arr.clone();
 
        // One by one move boundary of unsorted subarray
        for (int i = 0; i < n-1; i++){
            // compare proceeding element
            int val = i;
            for (int j = 0; j < n; j++){
                if (arr[val] > arr[j])
                    count++;
                    System.out.println(count);
            }
            tempArr[count] = arr[val];
            count = 0;//reset counter
        }
      for (int i = 0; i < n; ++i)
            System.out.print(tempArr[i] + " ");
    }
   public static void main(String args[]){
     
   int a[] = {50, 40, 30, 20, 10};
   sort(a);
   }
}

我假設這會將 arrays 排序到另一個數組中,但存在索引 0 不會改變的問題。 這使用一種將當前值與數組中的所有元素進行比較的方法。 然后使用 count 作為索引,如果當前鍵大於當前值,則遞增它。

問題是它在最后部分增加

0
1
2
3
4
0
0
1
2
3
0
0
0
1
2
0
0
0
0
1  //IT INCREMENTED 
50 20 30 40 50 

您的第一個循環從0開始,第二個循環也從0開始,這是一個問題,但它應該是01 將第二個循環j = 0的初始化更改為j = val + 1 它可以解決您的問題。

下面是修改后的代碼:

public class Main
{
    public static void sort(int arr[])
    {
        int n = arr.length;
        int count = 0;
        int tempArr [] = arr.clone();
 
        for (int i = 0; i < n; i++){
            int val = i;
            for (int j = val + 1; j < n; j++){
                if (arr[i] > arr[j])
                    count++;
                    System.out.println(count);
            }
            tempArr[count] = arr[val];
            count = 0;
        }
      for (int i = 0; i < n; ++i)
            System.out.print("\n" + tempArr[i] + " ");
    }
    public static void main(String args[]){
     
        int a[] = {50, 40, 30, 20, 10};
        sort(a);
    }
}

如果你想讓你的代碼簡單,那么使用 java 內置方法Arrays.sort(arrray)

import java.util.*;
public class Main
{
    public static void sort(int arr[])
    {
        Arrays.sort(arr);
        System.out.println(Arrays.toString(arr));
    }
    public static void main(String args[]){
     
        int a[] = {50, 40, 30, 20, 10};
        sort(a);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM