如何编写按降序排列的 selectionSort 方法?
How to write a selectionSort method going in Descending order?
您好!目前,我对我的代码有点困惑。我想按降序移动我的数组。这听起来很简单,但出于某种原因,我无法理解这种方法。目前,这是我编写的一个直接按升序排列的 selectionSort 方法。当谈到降序时,我不确定从哪里开始。关于如何反转方程式,我通常会溢出,因为它应该使用数组的原始“.length”。
非常感谢您的帮助!
int[] arr = {5, 3, 2, 44, 1, 75, 23, 15};
private static void descendingSort (int[] arr) {
for ( int i = 0; i < arr.length - 1; i++) {
int smallestIndex = i;
for ( int j = i + 1; j < arr.length; j++) {
//searching for smallest...
//if statement declaring if arr is smaller than the index[0]
if (arr[j] < arr[smallestIndex]) {
//now it has changed to pickle because it has swapped. thx u
smallestIndex = j;
}
}
}
}
如果您想快速解决问题,请按以下方法处理。
请注意,我们只是更改了几行。
具体...
- 我们仍然找到最小的元素
- 我们放在后面而不是前面
- 两个循环中的迭代顺序是
back-to-front
而不是front-to-back
更简单的实现方法是按升序对元素进行排序,然后反转数组。
void selectionSortDescending(int arr[])
{
int n = arr.length;
// Start by finding the smallest element to put in the very back
// One by one move boundary of unsorted subarray
for (int i = n-1; i >= 0; i--)
{
// Find the minimum element in unsorted array
int min_idx = i;
for (int j = i-1; j >= 0; j--)
if (arr[j] < arr[min_idx])
min_idx = j;
// Swap the found minimum element with the last element
int temp = arr[min_idx];
arr[min_idx] = arr[i];
arr[i] = temp;
}
}
您好!目前,我对我的代码有点困惑。我想按降序移动我的数组。这听起来很简单,但出于某种原因,我无法理解这种方法。目前,这是我编写的一个直接按升序排列的 selectionSort 方法。当谈到降序时,我不确定从哪里开始。关于如何反转方程式,我通常会溢出,因为它应该使用数组的原始“.length”。
非常感谢您的帮助!
int[] arr = {5, 3, 2, 44, 1, 75, 23, 15};
private static void descendingSort (int[] arr) {
for ( int i = 0; i < arr.length - 1; i++) {
int smallestIndex = i;
for ( int j = i + 1; j < arr.length; j++) {
//searching for smallest...
//if statement declaring if arr is smaller than the index[0]
if (arr[j] < arr[smallestIndex]) {
//now it has changed to pickle because it has swapped. thx u
smallestIndex = j;
}
}
}
}
如果您想快速解决问题,请按以下方法处理。 请注意,我们只是更改了几行。
具体...
- 我们仍然找到最小的元素
- 我们放在后面而不是前面
- 两个循环中的迭代顺序是
back-to-front
而不是front-to-back
更简单的实现方法是按升序对元素进行排序,然后反转数组。
void selectionSortDescending(int arr[])
{
int n = arr.length;
// Start by finding the smallest element to put in the very back
// One by one move boundary of unsorted subarray
for (int i = n-1; i >= 0; i--)
{
// Find the minimum element in unsorted array
int min_idx = i;
for (int j = i-1; j >= 0; j--)
if (arr[j] < arr[min_idx])
min_idx = j;
// Swap the found minimum element with the last element
int temp = arr[min_idx];
arr[min_idx] = arr[i];
arr[i] = temp;
}
}