gpt4 book ai didi

java - 对整数数组进行排序(使用我自己的算法)- Java

转载 作者:行者123 更新时间:2023-12-01 07:34:55 26 4
gpt4 key购买 nike

我正在为我的编程课做额外的学分作业。我们正在做 OOP,这个例子是获取一个数组并对其进行排序。所有的排序代码都会进入add方法。我已经有了一些代码,并且可以正常工作。正如标题中所说,我必须用我独特的代码创建我自己的算法。如何对列表中的所有整数从小到大进行排序? (整数是使用 add 方法添加的值。)这是讲师给我的说明:

• 沿着数组走下去,直到找到新元素应该所在的位置。由于名单已经排序后,您可以继续查看元素,直到找到至少与要排序的元素一样大的元素已插入。

• 向下移动新元素之后的每个元素,即从您停止的元素开始的所有元素一直到最后。这将创建一个槽,您可以在其中放置新元素。请注意顺序您移动它们,否则您将覆盖您的数据!

现在您可以将新元素插入到最初停止的位置。所有这些都将进入您的 add 方法。

程序的两个类:

   private int[] list;
private int numElements = 0;



//-------------------------------------------------------------
// Constructor -- creates an integer list of a given size.
//-------------------------------------------------------------
public IntList(int size)
{
list = new int[size];
}
//------------------------------------------------------------
// Adds an integer to the list. If the list is full,
// prints a message and does nothing.
//------------------------------------------------------------

public void add(int value)
{
if (numElements == list.length){
System.out.println("Can't add, list is full");
}
else
{
list[numElements] = value;
for(int i = 0; i < numElements; i++){
//May be I should use a nested loop?
//for(k = 0; k <)
if(value < list[i]){
list[i+1]= list[i];
list[i]=value;
}
}
numElements++;

}


}



//-------------------------------------------------------------
// Returns a string containing the elements of the list with their
// indices.
//-------------------------------------------------------------
public String toString()
{
String returnString = "";
for (int i=0; i<numElements; i++)
returnString += i + ": " + list[i] + "\n";
return returnString;
}
}

另一类:

public class IntListThing {


public static void main(String[] args){

IntList myList = new IntList(10);
myList.add(84);
myList.add(27);
myList.add(250);
myList.add(18);
myList.add(94);
myList.add(8);
myList.add(87);
System.out.println(myList);
}
}

最佳答案

一旦您找到正确的位置,即 if(value < list[i]){为真然后将所有可用元素向右移动。您仅使用 list[i+1]= list[i]; 移动一个.

即使用一个小循环:

  for(int j= numElements-1; j>=i; j--){
list[j+1]= list[j];
}
list[i] = value;

请注意:这是概念。请调整索引和条件。

编辑:我没有提到插入元素后需要立即中断。我还更正了条件。这是更新后的else block 代码。

        list[numElements] = value;
for(int i = 0; i < numElements; i++){
//May be I should use a nested loop?
//for(k = 0; k <)
if(value < list[i]){
for(int j= numElements-1; j>=i; j--){
list[j+1]= list[j];
}
list[i] = value;
break;
}
}
numElements++;

关于java - 对整数数组进行排序(使用我自己的算法)- Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13315690/

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