Endi har bir o'tish uchun biz hozirgi elementni uning oldingi elementlari bilan taqqoslaymiz. Shunday qilib, birinchi o'tishda biz ikkinchi elementdan boshlaymiz.
Shunday qilib, N elementlari bo'lgan massivni to'liq tartiblash uchun biz N soni o'tishini talab qilamiz.
C ++ dan foydalanib, Insertion Sort texnikasini amalga oshiramiz.
#include using namespace std;
int main ()
{
int myarray[5] = { 12,4,3,1,15};
cout<<"\nInput list is \n";
for(int i=0;i<5;i++)
{
cout <}
for(int k=1; k<5; k++)
{
int temp = myarray[k];
int j= k-1;
while(j>=0 && temp <= myarray[j])
{
myarray[j+1] = myarray[j];
j = j-1;
}
myarray[j+1] = temp;
}
cout<<"\nSorted list is \n";
for(int i=0;i<5;i++)
{
cout <}
}
Chiqish natijasi: Kirish ro'yxati bu
12 4 3 1 15
Saralangan ro'yxat
1 3 4 12 15
Yuqoridagi chiqish kiritish tartibida ishlatilgan to'liq tartiblangan qatorni ko'rsatadi.
6.Quick sort Quicksort - ma'lumotlarni saralash uchun ishlatilishi mumkin bo'lgan eng samarali algoritm. Ushbu usulda "bo'linish va g'alaba qozonish" strategiyasidan foydalaniladi, bunda muammo bir nechta kichik dasturlarga bo'linadi va ushbu kichik dasturlarni echib bo'lgandan so'ng ular to'liq tartiblangan ro'yxat uchun birlashtiriladi.
C ++ yordamida tezkor tartiblash texnikasini amalga oshiramiz.
#include using namespace std;
// Swap two elements - Utility function
void swap(int* a, int* b)
{
int t = *a;
*a = *b;
*b = t;
}
// partition the array using last element as pivot
int partition (int arr[], int low, int high)
{
int i = (low - 1);
for (int j = low; j <= high- 1; j++)
{
//if current element is smaller than pivot, increment the low element
//swap elements at i and j
if (arr[j] <= pivot)
{
i++; // increment index of smaller element
swap(&arr[i], &arr[j]);
}
}
swap(&arr[i + 1], &arr[high]);
return (i + 1);
}
//quicksort algorithm
void quickSort(int arr[], int low, int high)
{
if (low < high)
{
//partition the array
int pivot = partition(arr, low, high);
//sort the sub arrays independently
quickSort(arr, low, pivot - 1);
quickSort(arr, pivot + 1, high);
}
}
void displayArray(int arr[], int size)
{
int i;
for (i=0; i < size; i++)
cout<}
int main()
{
int arr[] = {12,23,3,43,51};
int n = sizeof(arr)/sizeof(arr[0]);
cout<<"Input array"<displayArray(arr,n);
cout<quickSort(arr, 0, n-1);
cout<<"Array sorted with quick sort"<displayArray(arr,n);
return 0;
}