[英]I don't know why my array doesn't have its random values saved in this bubble sort
I wanted to do a simple bubble sort exercise but I don't know what should I change in order to make this work but also not to screw with the drawing method that I have.我想做一个简单的冒泡排序练习,但我不知道我应该改变什么才能完成这项工作,但也不知道我拥有的绘图方法。 Here is my code:
这是我的代码:
package sorting;
import java.awt.Graphics;
import javax.swing.JFrame;
public class Sorting extends JFrame{
public int[] values = new int[800];
public static void main(String[] args) {
Sorting sort = new Sorting();
}
public Sorting(){
setSize(800, 500);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
setTitle("Sorting");
}
@Override
public void paint(Graphics g){
for (int i = 0; i < 800; i++){
values[i] = (int)(Math.random()*500);
for (int k = 0; k < 800; k++){
g.drawLine(k, 500, k, 500-values[k]);
}
}
for (int j = 0; j < 800; j++){
for (int a = 0; a < 800 - j - 1; a++){
int r = values[j];
int b = values[j + 1];
if (a > b){
swap(values, j, j+1);
}
}
}
}
private void swap(int[] arr, int a, int b) {
int temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
}
}
My guess is that my values array doesn't have the values created in paint method saved and that's why the swapping method isn't working but I'm not sure.我的猜测是我的 values 数组没有保存在paint方法中创建的值,这就是交换方法不起作用但我不确定的原因。
if (a > b){
swap(values, j, j+1);
}
Should be应该
if (r > b){
swap(values, j, j+1);
}
Following is the fixed for loop.以下是固定的 for 循环。 You are using incorrect index, as well as comparing incorrect values.
您使用了不正确的索引,以及比较了不正确的值。
for (int j = 0; j < 800; j++){
for (int a = 0; a < 800 - j - 1; a++){
int r = values[a];
int b = values[a + 1];
if (r > b){
swap(values, a, a+1);
}
}
}
In bubble sort you would be looping through whole array and if there is a pair of two numbers at index i
and i+1
that does not seem to be sorted, you swap values at those indexes and you proceed like that till the end of your current loop.在冒泡排序中,您将遍历整个数组,如果在索引
i
和i+1
处有一对似乎未排序的两个数字,则您交换这些索引处的值,然后继续执行直到结束电流回路。 Then you have to loop through again because there was a unsorted part detected.然后您必须再次循环,因为检测到未排序的部分。 The algorithm ends when you loop through all entries and you detect no change to the array.
当您遍历所有条目并且检测到数组没有变化时,算法结束。
I would propose to use simple buuble sort implementation with while
and for
loop :我建议在
while
和for
循环中使用简单的 buuble 排序实现:
boolean isSorted = false; // assume array is not sorted
while (!isSorted) { //repeat until array is sorted
isSorted = true; // assume array is sorted
for (int i = 0; i < values.length - 1; i++) { //loop through array
int a = values[i]; //get first value to compare
int b = values[i + 1]; // get second value to compare
if (a < b) { // if first value is less than second, swap them
swap(values, i, i + 1);
isSorted = false; // there was a change so array is not actually sorted! So we will have to loop through whole array again
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.