gpt4 book ai didi

java - 插入排序无法正常工作

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:29:55 24 4
gpt4 key购买 nike

package sort;

public class InsertionSort {
public static void main(String[] args) {
int[] input ={5,3,5,3,2,1}; // the input to be sorted.
int key; // the value that will be put into its place in the pass
int j = 0; // indexes to be
int i = 0; // used for sorting


for(j = 1; j < input.length; j++){
key = input[j];
for(i = j-1; i >= 0; i--){ // Look for a proper place for the key
if(i-1 < 0){
if(input[i] > key){ // Have you found that place ?
for(int k = j;k > i; k--){ // Begin shifting
input[k] = input[k-1];
} // Done Shifting
input[i] = key; // Insert the key in proper place
break;
}
}else{
if(input[i] > key && input[i-1] < key){ // Have you found that place ?
for(int k = j;k > i; k--){ // Begin shifting
input[k] = input[k-1];
} // Done Shifting
input[i] = key; // Insert the key in proper place
break;
}
}
}
}

for(int each : input){
System.out.println(each);
}
}
}

问题是如果我的输入有重复的数字,排序就会失败。

对于 int[] input ={5,3,5,3,2,1};,我得到 1 2 3 5 5 3
对于非重复数字,排序工作正常。

这里有什么问题吗?

最佳答案

public static void main(String[] args) {
int[] input = {12, 21, 21, 1, 4, 5, 66, 74, 0, -2, 5, 3, 5, 3, 2, 1}; // the input to be sorted.
int key; // the value that will be put into its place in the pass
int j = 0; // indexes to be
int i = 0; // used for sorting

for (i = 1; i < input.length; i++) {
key = input[i];
j = i;
while (j > 0 && input[j - 1] > key) {
input[j] = input[j - 1];
j--;
}
input[j] = key;
}

for (int each : input) {
System.out.println(each);
}
}

关于java - 插入排序无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18622334/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com