【发布时间】:2020-11-07 22:06:45
【问题描述】:
我有一个选择排序算法,它将 47 个不同的垂直红色条按从低到高的顺序排序。在排序过程中,我希望放置在正确位置的条变成蓝色。我想要这样做的方法是复制我的 barHeight 数组,对副本进行排序,然后查看原始数组条是否与已经排序的复制条匹配,而原始数组正在排序。我已经在我的 arrayCopy 方法中复制并排序了我的 barHeight 数组。在 drawBar 中,我有一个 if 语句,它说如果原始 barHeight 方法中的条与副本匹配,那么它将被绘制为蓝色,所以我认为我拥有一切,但程序只是无法正常工作。没有任何错误消息,但没有一个条变成蓝色,我不知道为什么。我究竟做错了什么?这是我的代码:
import java.util.*;
import java.awt.*;
import java.applet.*;
public class Lab15st extends Applet
{
private int numBars; // number of bars to be sorted
private int barHeight[]; // array of bar heights
private int sortDelay; // delay between comparison iteration
private int secondBarHeight[]; //copy of barHeight array
public void init()
{
numBars = 47;
sortDelay = 50; // Change to 50 is using the "Selection Sort".
barHeight = new int[numBars];
secondBarHeight = new int[numBars];
arrayCopy();
getBarValues();
}
public void getBarValues()
{
Random rand = new Random(3333);
for (int k = 0; k < numBars; k++)
barHeight[k] = rand.nextInt(591) + 10; // range of 10..600
}
public void arrayCopy()
{
int[] secondBarHeight = barHeight.clone();
for (int i = 0; i < numBars; i++) {
int min = secondBarHeight[i];
int minId = i;
for (int j = i+1; j < secondBarHeight.length; j++) {
if (secondBarHeight[j] < min) {
min = secondBarHeight[j];
minId = j;
}
}
int temp = secondBarHeight[i];
secondBarHeight[i] = min;
secondBarHeight[minId] = temp;
}
}
public void paint(Graphics g)
{
showFrame(g);
displayBars(g);
sortBars(g);
}
public void showFrame(Graphics g)
{
Expo.setBackground(g,Expo.black);
Expo.setColor(g,Expo.white);
Expo.fillRectangle(g,20,20,980,630);
}
public void drawBar(Graphics g, int k)
{
int y2 = 630;
int x1 = 35 + k * 20;
int y1 = y2 - barHeight[k];
int x2 = x1 + 10;
for (int i = 0; i < numBars; i++){
if(barHeight[i] == secondBarHeight[i])
Expo.setColor(g,Expo.blue);
else
Expo.setColor(g,Expo.red);
}
Expo.fillRectangle(g,x1,y1,x2,y2);
}
public void eraseBar(Graphics g, int k)
{
int y2 = 630;
int x1 = 35 + k * 20;
int y1 = y2 - barHeight[k];
int x2 = x1 + 10;
Expo.setColor(g,Expo.white);
Expo.fillRectangle(g,x1,y1,x2,y2);
}
public void displayBars(Graphics g)
{
for (int k = 0; k < numBars; k++)
drawBar(g,k);
}
public void swap(Graphics g, int m, int n)
{
Expo.delay(sortDelay);
eraseBar(g,m);
eraseBar(g,n);
int temp = barHeight[m];
barHeight[m] = barHeight[n];
barHeight[n] = temp;
drawBar(g,m);
drawBar(g,n);
}
public void sortBars(Graphics g)
{
for (int p = 0; p < numBars; p++)
{
int smallest = findSmallestItemIndex(p);
if (barHeight[p] != barHeight[smallest])
swap(g,p,smallest);
}
}
public int getItem(int index) {
return barHeight[index];
}
public int findSmallestItemIndex(int start)
{
int smallest = start;
for (int k = start+1; k < numBars; k++)
if (barHeight[k] < barHeight[smallest])
smallest = k;
return smallest;
}
}
【问题讨论】:
标签: java arrays sorting copy selection-sort