简体   繁体   English

JAVA中的这种排序叫什么?

[英]What do you call this kind of sorting in JAVA?

Hope that you guys are having a good day!希望你们今天过得愉快!

I'm new to Java so I'm still getting the hang of it.我是 Java 的新手,所以我仍然掌握它的窍门。

There is a sorting algorithm which I do use more often than not有一种我经常使用的排序算法

for(int i=0; i<array.length; i++){
    for(int j=i; j<array.length; j++){
        if(array[j] < array[i]){
            int temp = array[i];
            array[i] = array[j];
            array[j] = temp;
        }
    }
}

Explanation: The outer loop first use the first element of the array and start comparing that to the rest of the elements inside the list, if it is larger than one of the element, swap it.说明:外循环首先使用数组的第一个元素,并开始将其与列表中元素的 rest 进行比较,如果它大于其中一个元素,则交换它。

For example, we got an array 12, 5, 14, 8, 3例如,我们得到一个数组 12, 5, 14, 8, 3

We have array[0] as 12. Comparing that to array[1] in the inner loop, since 5<12 we swap them.我们有 array[0] 为 12。将其与内部循环中的 array[1] 进行比较,因为 5<12 我们交换它们。 The inner loop continues until array[4] where array[4] < array[0] now we have 3 as the smallest element in the array in the right place内部循环一直持续到 array[4],其中 array[4] < array[0] 现在我们有 3 作为数组中正确位置的最小元素

Rinse and repeat with the rest of the elements冲洗并重复元素 rest

What is this type of sorting?这种排序是什么? Because it doesn't seem to fit in Selection Sort or Insertion Sort let alone Bubble Sort.因为它似乎不适合选择排序或插入排序,更不用说冒泡排序了。

Thanks for helping!感谢您的帮助!

This is most definitely selection sort since at the end you're swapping a higher number near the beginning for a lower number further away. 这绝对是一种选择,因为最后您将在开头附近交换一个较高的数字,而在远处交换一个较小的数字。 Most of the time if a sort method has a swap at the end it's selection. 大多数情况下,如果排序方法的结尾处​​有交换,则它会被选中。

This is a kind of bubble sort .这是一种冒泡排序 A bubble sort would compare array[j-1] with array[j] , not array[i] with array[j] , but the overall effect is similar: The algorithm moves all larger elements to the right simultaneously, whereas a bubble sort moves each element in turn to the right until a larger element is encountered.冒泡排序会将array[j-1]array[j]进行比较,而不是将array[i]array[j]进行比较,但总体效果是相似的:该算法同时将所有较大的元素向右移动,而冒泡排序依次向右移动每个元素,直到遇到更大的元素。

It is not a selection sort, which starting at index 0, finds the smallest element from index onwards then swaps it with the element at index, then increments index and repeats for all indexes.不是选择排序,它从索引 0 开始,找到从索引开始的最小元素,然后将其与索引处的元素交换,然后递增索引并为所有索引重复。

Your code is a java implementation of a simplified and unoptimized version of this pseudocode .您的代码是此伪代码的简化和未优化版本的 java 实现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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