0% found this document useful (0 votes)
17 views3 pages

Record File - 15jULY

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views3 pages

Record File - 15jULY

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

SORTING ALGORITHMS

• BUBBLE
• INSERTION
• SELECTION

// Bubble sort in C++

#include<iostream>
using namespace std;
int main()
{
int n, i, arr[50], j, temp;
cout<<"Enter the Size (max. 50): ";
cin>>n;
cout<<"Enter "<<n<<" Numbers: ";
for(i=0; i<n; i++)
cin>>arr[i];
cout<<"\nSorUng the Array using Bubble Sort Technique..\n";
for(i=0; i<(n-1); i++)
{
for(j=0; j<(n-i-1); j++)
{
if(arr[j]>arr[j+1])
{
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
cout<<"\nArray Sorted Successfully!\n";
cout<<"\nThe New Array is: \n";
for(i=0; i<n; i++)
cout<<arr[i]<<" ";
cout<<endl;
return 0;
}
INSERTION SORT

#include<iostream>
using namespace std;
void inSort(int a[], int n)
{
int i,j, k;
for (i = 1; i < n; i++)
{
k = a[i];
j = i - 1;
/*Move elements of arr[0..i-1], that are
greater than k, to one posiUon ahead
of their current posiUon */
while (j >= 0 && a[j] > k)
{
a[j + 1] = a[j];
j = j - 1;
}
a[j + 1] = k;
}
}

void print(int a[], int n)


{
int i;
for (i = 0; i < n; i++)
cout << a[i] << " ";
cout << endl;
}

int main()
{
int a[] = { 15,2,8,7,3,5,4,1 };
int n = sizeof(a) / sizeof(a[0]);
inSort(a, n);
print(a, n);
return 0;
}
SELECTION SORT

#include<iostream>
using namespace std;

void selecUonSort(int array[], int size) {


int i, j, small,loc;
for(i = 0; i<size-1; i++) {
small = array[i];
loc = i;
for(j = i+1; j<=size-1; j++)
{
if(small > array[j])
{
small=array[j];
loc = j;
}
}
array[loc] = array[i];
array[i] = small;
}
}
int main() {
int i, n;
cout << "Enter the number of elements: ";
cin >> n;
int arr[n];
cout << "Enter elements:" << endl;
for(i = 0; i<n; i++) {
cin >> arr[i];
}
cout << "Array before SorUng: ";
for(i=0;i<n;i++)
{
cout<<arr[i]<<"\t";
}
selecUonSort(arr, n);
cout << "\nArray aher SorUng: ";
for(i=0;i<n;i++)
{
cout<<arr[i]<<"\t";
}

You might also like