Get the App
SLTechnology News&Howtos  ›  Development  › 

What is the sorting algorithm directly inserted in C language?

Shulou Source: shulou.com Published: 2022-06-02 03:58:23 09月19日 Update

This article will explain in detail what the sorting algorithm for direct insertion in C language is, and the content of the article is of high quality, so the editor will share it for you as a reference. I hope you will have some understanding of the relevant knowledge after reading this article.

1. Algorithm template void InsertSort (SqList * L) {int j; for (int I = 2; i length; i + +) {if (L-> arr [I])

< L->

Arr [I-1]) {L-> arr [0] = L-> arr [I]; / set Sentinel for (j = iMur1; L-> arr [j] > L-> arr [0]; j -) L-> arr [j + 1] = L-> arr [j]; L-> arr [j + 1] = L-> arr [0];}} 2. Introduction of algorithm

The basic idea of direct insertion sorting is: for a sequence of length n, starting from the second element, insert new elements into the previously arranged sequence one by one (the first element can be regarded as an ordered subsequence of length 1). As a result, an ordered sequence of length n is obtained.

The time complexity of the algorithm is O (n ^ 2), the best case is that the sequence to be sorted is ordered, it only needs to be traversed once, the time complexity is O (n), and the worst case is reverse order, the time complexity is O (n ^ n). Because the elements are compared one by one, direct insertion sorting is a stable sorting algorithm.

3. Example # include using namespace std;const int N = 100 int arr typedef struct {int arr [N]; int length;} SqList;void InsertSort (SqList * L) {int j; for (int I = 2; i length; i + +) {if (L-> arr [I])

< L->

Arr [I-1]) {L-> arr [0] = L-> arr [I]; / set Sentinel for (j = iMur1; L-> arr [j] > L-> arr [0]; j -) L-> arr [j + 1] = L-> arr [j]; L-> arr [j + 1] = L-> arr [0] } int main () {SqList L; L.arr [1] = 50; L.arr [2] = 10; L.arr [3] = 90; L.arr [4] = 30; L.arr [5] = 70; L.arr [6] = 40; L.arr [7] = 80; L.arr [8] = 60; L.arr [9] = 20; L.length = 9 InsertSort (& L); for (int I = 1; I

Tags: Algorithms sorting elements sequences complexity order complexity time length language content Sentinels situations articles more knowledge articles good between examples Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Xiaomi Docker Shulou Information MySQL vpn