【发布时间】:2021-04-14 16:46:44
【问题描述】:
我被困在对数组进行排序(当然,不允许使用方法的一部分)。
随机生成数字的数组应该被排序和打印: 偶数(升序 - 奇数(降序)
发件人:830 281 380 162 679 587 944 143 940 862 546 730
至:162 380 546 730 830 862 940 944 - 679 587 281 143
我已经设法将偶数和赔率分开并对偶数进行排序,但在排序赔率时遇到了困难。
意识到我可能不是通过在两个不同的部分中单独排序来做到这一点的最有效的方法,但如果你能指出哪里出了问题,我将不胜感激。
想法是计算奇数和偶数,并使用这些数字来知道数组中的哪个位置进行循环排序,但这是在奇数部分失败。
对不起,frakencode...
int[] arr = new int[amountRandom];
for (int i = 0; i < amountRandom; i++)
{
arr[i] = (int) (Math.random() * 1000);
}
int checkEvenOdd;
int evenAmount = 0;
int oddAmount = 0;
for(int i = 0; i < arr.length; i++)
{
checkEvenOdd = arr[i] % 2;
if(checkEvenOdd == 0)
{
evenAmount++;
}
else
{
oddAmount++;
}
}
int arrLeft = 0;
int arrRight;
arrRight = arr.length - 1;
while(arrLeft < arrRight) {
while(arr[arrLeft] % 2 == 0 && arrLeft < arrRight) {
arrLeft++;
}
while(arr[arrRight] % 2 != 0 && arrLeft < arrRight) {
arrRight--;
}
if(arrLeft < arrRight) {
int x = arr[arrLeft];
arr[arrLeft] = arr[arrRight];
arr[arrRight] = x;
arrLeft++;
arrRight--;
}
}
int i, j, minValue, minIndex, temp = 0;
for (i = 0; i < evenAmount; i++) {
minValue = arr[i];
minIndex = i;
for (j = i; j < evenAmount; j++) {
if (arr[j] < minValue) {
minValue = arr[j];
minIndex = j;
}
}
if (minValue < arr[i]) {
temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
}
}
int maxValue, maxIndex, temp2 = 0;
**for (i = evenAmount; i < amountRandom; i++)** {
maxValue = arr[i];
maxIndex = i;
for (j = i; j > oddAmount; j++) {
if (arr[j] > maxValue) {
maxValue = arr[j];
maxIndex = j;
}
}
if (maxValue > arr[i]) {
temp2 = arr[i];
arr[i] = arr[maxIndex];
arr[maxIndex] = temp2;
}
}
【问题讨论】: