# Basic sorting algorithm

1. Bubble sort algorithm (time complexity O(n))

1. Assuming there are N numbers, the exchange range is 0~N-1 at the beginning, the larger one is placed behind, the last one is exchanged in turn, and the last one is placed at the end.
2. Next, reduce the range to 0~N-2. Continue comparing the bigger one, put it behind, swap the past one by one, and the second largest one is placed next to last
3. The entire array is ordered until the range is reduced to a single number
```int *bublesort(int *arry, int n)
{
if(arry==NULL || n<2)
{
return arry;
}
int i = 0, j = 0;
int temp;

for(i=0; i<n-1; i++)
{
for(j=0; j<n-i-1; j++)
{
if(arry[j] > arry[j+1])
{
temp = arry[j];
arry]j] = arry[j+1];
arry[j+1] = temp;
}
}
}
return arry;
}

for (int i = n - 1; i >= 0; i--)
{
for (int j = 0; j < i; j++)
{
if (arr[j] > arr[j + 1])
{
swap(arr, j, j + 1);
}
}
}

```

2. Selective Sorting (Time Complexity O(n))

1. Start by picking a minimum from the range 0~N-1 of the entire array and placing it at position 0
2. Then select the smallest value from the range 1~N-1 and place it at position 1
3. The entire array is ordered until the last number is included
```int *SelectSort(int *a, int n)
{
if(a==NULL || n<2)
{
return a;
}

int i,j;
int min;
int temp;
for(i=0; i<n; i++)
{
min = i;
for(j=i+1; j<n; j++)
{
if(a[min] > a[j])
{
min = j;
}
}
if(min != i)
{
temp = a[min];
a[min] = a[i];
a[i] = temp;
}
}

return a;
}```

3. Insert Sort Procedure (O(n))

1. First the number at position 1 is compared to the number at position 0, and if the number at position 1 is smaller, it is exchanged with the number at position 0
2. The next number at position 2 is swapped if it is smaller than the number before it
3. Assuming the number of position K is b, B is compared with the previous number once until b>=the number before it stops
4. Repeat the process from position 1 to position N-1, and the whole array is ordered
```int *InsertSort(int *a, int n)
{
if(a==NULL || n<2)
{
return a;
}

int i, j;
int temp;
for(i=1; i<n; i++)
{
for(j=i; j>0; j--)
{
if(a[j] < a[j-1])
{
temp = a[j];
a[j] = a[j-1];
a[j-1] = temp;
}
else
{
break;
}
}
}
return a;
}

```

Posted by Skittlewidth on Thu, 30 Jan 2020 08:38:54 -0800