What kind is this? - Java

Does anyone know what kind of this is in java? I'm not quite sure. Insert? a choice? Thanks in advance!

    public class sorting {
      public static void main(String[] args)
      {
      String[] arr = {"Banana", "Apple", "Orange", "Fruit", "Watermelon", "Hello World"};
        String tmp;
        for (int i = 0;i < arr.length;i++)
        {
          tmp = arr[i];
          for (int j = 0;j < arr.length;j++)
          {
            if (i == j) continue;
            int x = tmp.compareTo(arr[j]);
            if (x < 0)
            {
              tmp = arr[j];
              arr[j] = arr[i];
              arr[i] = tmp;
            }
          }
        }
        for (int i = 0;i < arr.length;i++)
          System.out.println(arr[i]);
      }
    }
+3
source share
3 answers

It looks like bubble sort :

  • it O(n^2)
  • At each step, the largest element “bubbles” to the correct position
  • A swap is performed to bubble the elements.

Although Bubble sorting is ugly, we can do a little less work by setting indexes properly and eliminating the comparison i == jin the process:

for (int i = arr.length; i > 0; i--) {
    for (int j = 0; j < i - 1; j++) {
        int x = arr[j].compareTo(arr[j + 1]);
        if (x > 0) {
            tmp = arr[j];
            arr[j] = arr[j + 1];
            arr[j + 1] = tmp;
        }

    }
}
+1
source

Sorting bubbles. The lexicographic view of the bubble, to be specific.

+1
source
for (int i = 0;i < arr.length;i++)
{//outer loop
    tmp = arr[i];
    for (int j = 0;j < arr.length;j++)
    {//inner loop
        if (i == j) continue;
        int x = tmp.compareTo(arr[j]);
        if (x < 0)
        {
            tmp = arr[j];
            arr[j] = arr[i];
            arr[i] = tmp;
        }
    }
}

As you could say, in the inner loop, it compares with the node side by side and moves just one step.
Each time it will be launched from the index of the outer loop and again retrieved through the rest of the data.
It seems to be a bubble, but it is a strange tool.

0
source

All Articles