使用 For 循环手动对数组进行排序 - Java
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34745203/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using a For Loop to Manually Sort an Array - Java
提问by Evan
I'm having trouble manually sorting the array with a for loop. It works except for the first and last number. Here's my code:
我在使用 for 循环手动对数组进行排序时遇到问题。除了第一个和最后一个数字外,它都有效。这是我的代码:
Scanner numInput = new Scanner(System.in);
int tempVar, num;
String numbersString;
int[] numbers = {4, 11, 13, 12, 17, 35, 15, 7, 19, 3, 45};
for (int i = 0; i < numbers.length - 1; i++)
{
for(int j = 0; j < numbers.length - 1; j++)
{
if(numbers[i] < numbers[j + 1])
{
tempVar = numbers [j + 1];
numbers [j + 1]= numbers [i];
numbers [i] = tempVar;
}
}
}
numbersString = Arrays.toString(numbers);
System.out.println(numbersString);
回答by amkz
Try this one:
试试这个:
int temp = 0;
for (int i = 0; i < numbers.length - 1; i++) {
for (int j = i + 1; j < numbers.length; j++) {
if (numbers[i] > numbers[j]) {
temp = numbers[j];
numbers[j] = numbers[i];
numbers[i] = temp;
}
}
}
You have little wrong second for iteration and reverse condition.
对于迭代和反向条件,您几乎没有错误的秒。
回答by melli-182
you have some errors in your code. I make some modifications, please look:
您的代码中有一些错误。我做了一些修改,请看:
int tempVar, num;
String numbersString;
int[] numbers = {4, 11, 13, 12, 17, 35, 15, 7, 19, 3, 45};
for (int i = 0; i < numbers.length; i++) {
for (int j = i; j < numbers.length; j++) {
if (numbers[i] < numbers[j]) {
tempVar = numbers[i];
numbers[i] = numbers[j];
numbers[j] = tempVar;
}
}
}
numbersString = Arrays.toString(numbers);
System.out.println(numbersString);
First, I recommend you to iterate in the second loop, from i(beacause the items previous i are now sorted).
首先,我建议您从i 开始在第二个循环中进行迭代(因为i之前的项目现在已排序)。
Second, you have to switch the items on iand jpositions.
其次,您必须在i和j位置上切换项目。
Finally, beacause you use <strict comparator un your loops break, you have to go user numbers.lengthand not numbers.length - 1.
最后,因为您在循环中断时使用了<strict compare ,所以您必须使用 user numbers.length而不是numbers.length - 1。
For more information, please see the buble sort algorithm
有关更多信息,请参阅冒泡排序算法
回答by KoenC
I believe what you are willing to do is selection sort? https://en.wikipedia.org/wiki/Selection_sortAn other option I see is bubble sort but I'll try to explain selection sort.
我相信你愿意做的是选择排序?https://en.wikipedia.org/wiki/Selection_sort我看到的另一个选项是冒泡排序,但我会尝试解释选择排序。
So the first iteration of the outer for loop, the one with i, you check the whole array for the smallest number with the inner for loop, the one with j, and you put the smallest number upfront in the array. During the second iteration of the outer for loop you only go over the numbers you haven't checked yet, which is the second number through the last number. During the third iteration you go over the third number through the last number and so on. Here's how I adjusted your code, I adjusted the inner for loop so with each iteration you check a smaller sub-list and adjusted your if clause so that the smallest number is found:
因此,外部 for 循环的第一次迭代,即带有 i 的循环,您使用内部 for 循环检查整个数组中的最小数字,即带有 j 的循环,然后将最小的数字放在数组中。在外部 for 循环的第二次迭代期间,您只检查尚未检查的数字,即第二个数字到最后一个数字。在第三次迭代期间,您将遍历第三个数字到最后一个数字,依此类推。这是我调整您的代码的方式,我调整了内部 for 循环,以便在每次迭代时检查一个较小的子列表并调整您的 if 子句,以便找到最小的数字:
int tempVar;
String numbersString;
int[] numbers = {4, 11, 13, 12, 17, 35, 15, 7, 19, 3, 45};
for (int i = 0; i < numbers.length - 1; i++)
{
// each iteration i you would need to go over a smaller array, so you set j = i each time
for(int j = i; j < numbers.length - 1; j++){
// checking if numbers[i] is greater than numbers[j + 1] instead of smaller than
if(numbers[i] > numbers[j + 1]){
tempVar = numbers [j + 1];
numbers [j + 1]= numbers [i];
numbers [i] = tempVar;
}
}
}
numbersString = Arrays.toString(numbers);
System.out.println(numbersString);
回答by Alderath
I will provide a modified version of your code with the intention of explaining why your code does not work. First, we need to decide specifically what we want to do. Lets say we want to sort the numbers in descendingorder.
我将提供您的代码的修改版本,以解释为什么您的代码不起作用。首先,我们需要具体决定我们想要做什么。假设我们要按降序对数字进行排序。
What does this mean? Every time when we are comparing two values at lowIndexand highIndex, we want to make sure that the value at lowIndexis higher than the value at highIndex.
这是什么意思?当我们在比较两个值每次lowIndex和highIndex,我们要确保在价值lowIndex比在值高highIndex。
The problem with your code is that it does not keep track of which index, i
or j+1
, that is lower.
您的代码的问题在于它没有跟踪哪个索引i
或哪个索引j+1
更低。
- When
i==1
andj+1==2
, your code will swap the values so that the greatestvalue out of numbers[1] and numbers[2] will be put at index 1. - When
i==2
andj+1==1
, your code will swap the values so that the smallestvalue out of numbers[1] and numbers[2] will be put at index 1.
- 当
i==1
和j+1==2
,你的代码将交换值,以便最大的价值了数字[1]和数字[2]将在索引1付诸表决。 - 当
i==2
and 时j+1==1
,您的代码将交换值,以便将numbers[1] 和 numbers[2]中的最小值放在索引 1 处。
This is incosistent. The algorithm is competing with itself, trying to move values in different directions. If we modify your code to check that we are consistent in whether we want to swap large values towards the beginning of the array or towards the end, your algorithm will start to work:
这是不一致的。该算法正在与自己竞争,试图在不同的方向移动值。如果我们修改您的代码以检查我们是否要在数组的开头或结尾交换大值是一致的,您的算法将开始工作:
for (int i = 0; i < numbers.length - 1; i++)
{
for(int j = 0; j < numbers.length - 1; j++)
{
if(numbers[i] < numbers[j + 1] && i < (j + 1)) //NOTE: additional condition for indices
{
tempVar = numbers [j + 1];
numbers [j + 1]= numbers [i];
numbers [i] = tempVar;
}
}
}
Note, however, that the example above is just for explaining what goes wrong in execution of your code. Rather than using this code, it would probably be more appropriate to use one of the other answers to this question, or study and compare sorting algorithms on wikipedia
但是请注意,上面的示例仅用于解释执行代码时出了什么问题。与其使用此代码,不如使用此问题的其他答案之一,或研究和比较维基百科上的排序算法可能更合适
回答by user7620657
Try this
尝试这个
class desc
{
void printArray(int arr[], int n)
{
for (int i = 0; i < n; i++)
{
System.out.print(" "+arr[i]);
}
}
void sort(int arr[],int n)
{
for (int i = 1; i < n; i++)
{
if(arr[i] < arr[i - 1] )
{
arr[i] = arr[i] + arr[i - 1];
arr[i - 1] = arr[i] - arr[i - 1];
arr[i] = arr[i] - arr[i - 1];
i=0;
}
}
}
public static void main(String []args)throws Exception
{
int[] arr = {-5, 0, -7, -2, -5, 1, -9, -1};
int n = arr.length;
desc d=new desc();
d.sort(arr,n);
d.printArray(arr, n);
}
}
回答by Baseer Ul Hassan
for (int i = 0; i < numbers.length - 1; i++)
{
for(int j = 0; j < numbers.length - 1; j++)
{
if(numbers[i] < numbers[j ]) //NOTE: additional condition for indices
{
tempVar = numbers [j ];
numbers [j ]= numbers [i];
numbers [i] = tempVar;
}
}
}
use it
用它
回答by Geno Papashvili
public int[] sort(int[] arr) {
int marker, i, temp;
marker =0;
i = 1;
while (marker < arr.length - 1) {
if (i == arr.length) {
marker++;
i = marker;
}
if (arr[marker] > arr[i]) {
temp = arr[marker];
arr[marker] = arr[i];
arr[i] = temp;
}
i++;
}
return arr;
}
回答by apoori
You have to initialize the value for j as i+1, this sorting algorithm is called bubble sort, that works by repeatedly swapping the adjacent elements if they are in wrong order. The below method is always runs O(n^2) time even if the array is sorted.
您必须将 j 的值初始化为 i+1,这种排序算法称为冒泡排序,它通过重复交换相邻元素(如果它们的顺序错误)来工作。即使数组已排序,以下方法也始终运行 O(n^2) 时间。
public static void main (String[] args)
{
int[] array = {4,2,1,3,5,9,6,8,7};
for(int i = 0 ; i < array.length;i++)
{
for(int j = i+1 ; j< array.length;j++)
{
if(array[i] > array[j])
{
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}