简体   繁体   中英

Swapping lowest value in the array to order from least to greatest

I have this code

public static int[] swapLowest(int[] array)
{
    int smallestValue = 0;
    for(int i = 0; i < array.length; i++)
    {
        for(int k = i + 1; k < array.length; k++)
        {
            if(array[i] > array[k])
            {
                smallestValue = array[i];
                array[i] = array[k];
                array[k] = smallestValue;
            }
        }
    }
}

and it works how I want it to: swapping values to make it from least to greatest (eg [5, 1, 2, 1, 6] would turn to [1, 1, 2, 5, 6]).

However, the logic behind this is wrong. Apparently, I did not meet the criteria:

  • Find the smallest number in the array from the starting point
  • Swap the lowest value with the current value, if necessary
  • Move to the next index
  • Repeat until it reaches the last index

I'm not too sure why. Did I understand it wrong? Regardless, I need to fix my code, and any pointers to help me understand/what to do instead will be greatly appreciated

Seems like you are trying to write a variation of selection sort (exchange sort) and there is nothing wring with your code. There are couple of ways you could implement selection sort.

  1. swap the elements outside the inner for loop
  2. swap the elements inside the inner for loop

you are following up the second method

inside your inner for loop you are looking for the smallest value compared to your current value and if there is a one you are swapping them.

But regarding the time complexity second method (which you have used) could be bit more expensive. Because rather than finding the lowest element in the array and swapping with it, you swap elements every time there is an lower element compared to your current element inside the inner loop.

What you could do is record the index if it's lower than your element and continue to traverse the array inside the inner for loop checking if there are other elements lower than the current (if there are update the lowest element index)and once you found it and out of inner loop you could swap the elements.

public static int[] swapLowest(int[] array)
    {
        for(int i = 0; i < array.length; i++)
        {
            int index = i;
            for(int k = i + 1; k < array.length; k++)
            {
                if(array[index] > array[k])
                {
                    index = k;
                }
            }
            int smallestValue = array[index];
            array[index] = array[i];
            array[i] = smallestValue;
        }
        return array;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM