gpt4 book ai didi

java - 为什么我的排序算法不起作用?

转载 作者:搜寻专家 更新时间:2023-10-31 20:29:42 25 4
gpt4 key购买 nike

<分区>

代码应该这样做:a) 给定一个未排序的整数数组,您的任务是通过应用以下算法对数组进行排序(假设输入不包含重复项):从数组中的第一个元素开始执行以下步骤:– 计算较小元素的数量以找到正确的位置 i。– 如果元素在其正确位置,则移动到后续元素。– 否则,将当前元素与位置 i 中找到的元素交换。– 重复前面的步骤,直到到达最后一个元素。

例子:5 7 3 6 9检查 a[0],有一个元素比它小,所以它应该与元素交换位置1。7 5 3 6 9检查新元素 a[0]。它应该移动到位置 3。6 5 3 7 9检查新元素 a[0]。它应该移动到位置 2。3 5 6 7 9检查新元素 a[0]。它位于正确的位置,因此我们移动到后续元素 a[1]。

public class  Assignment1_T11_25_2729_Sara_Aly {
private int[] a;
private int max;
private int n;
int position=0;
public Assignment1_T11_25_2729_Sara_Aly (int max){
a= new int[max];
}
public void insert(int x){
a[n]=x;
n++;
}
public void sort(){
int out=0, smaller=0;
while(out<n){
for(int in=out+1;in<n;n++){
if(a[in]<a[out])
smaller++;
}
if (smaller==0){
out++;
}
else {
swap(a[out], a[smaller]);
}
}
}
private void swap (int one, int two){
int temp=a[one];
a[one]=a[two];
a[two]=temp;
}
public void display(){
for (int i=0;i<n;i++){
System.out.print(a[i]+ " ");
}
System.out.println("");
}
public static void main(String[]args){
int maxsize=5;
Assignment1_T11_25_2729_Sara_Aly trial;
trial= new Assignment1_T11_25_2729_Sara_Aly(maxsize);
trial.insert(5);
trial.insert(7);
trial.insert(3);
trial.insert(6);
trial.insert(9);
trial.display();
trial.sort();
trial.display();
}
}

Tried a few algorithims to get it to work but for some reason it won't sort any suggestions??

也尝试了这种排序方法,但没有成功。

public void sort(){
boolean finished = false;
int position =0;
while (position<max){
if (finished==true){
position++;
finished =false;
}
else {
int smaller=0;
for (int j = position+1; j<max; j++){
int temp=a[position];
if (a[j] <a[position]){
smaller++;
}
}
if (smaller==0){
finished= true;
}
else {
int temp= a[smaller];
a[smaller]=a[position];
a[position]=temp;
}
}
}
}

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