插入排序 Insertion sort

适用于n较小,基本有序的情况下

时间复杂度为 O(n2),稳定排序,辅助空间为 O(1);

static void insertion_sort(int[] unsorted) {
            for (int i = 1; i < unsorted.Length; i++) {
                if (unsorted[i - 1] > unsorted[i]) {
                    int temp = unsorted[i];
                    int j = i;
                    while (j > 0 && unsorted[j - 1] > temp) {
                        unsorted[j] = unsorted[j - 1];
                        j--;
                    }
                    unsorted[j] = temp;
                }
            }
        }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容