Bubble Sort and Selection Sort Updated
Bubble Sort and Selection Sort Updated
12 23 15 35 11
12 23 15 11 35
2nd Iteration
12 23 15 11 35
12 15 23 11 35
12 15 11 23 35
3rd Iteration
12 15 11 23 35
12 11 15 23 35
4th Iteration
12 11 15 23 35
11 12 15 23 35
11 12 15 23 35
Algorithm
Bubble_Sort ( A [ ] , N )
• Step 1: Start
• Step 2: Take an array of n elements
• Step 3: for i=0,………….n-1
• Step 4: for j=0,…….n-1
• Step 5: if arr[j]>arr[j+1] then Interchange arr[j]
and arr[j+1] End of if
• Step 6: Print the sorted array arr
• Step 7:Stop
Program No 1
#include<iostream>
using namespace std;
int main ()
{
int a[10],n,i,j,b,k,temp;
cout<<"Enter the size of array"<<endl;
cin>>n;
for(i=0;i<n;i++)
{
cout<<"Enter the elements"<<endl;
cin>>a[i];
}
for(b=0;b<n-1;b++)
{
for (k=0;k<n-1;k++)
if (a[k]>a[k+1])
{
temp=a[k];
a[k]=a[k+1];
a[k+1]=temp;
}
}
cout<<"Sorted Array values are"<<endl;
for(j=0;j<n;j++)
{
cout<<a[j]<<"\t";
}
return 0;
}
Selection Sort
• This method is used for sorting arrays in
ascending or in descending order.
• Selection sort arrange n elements of array by
placing the smallest element in proper
position in case of ascending order.
• If an array has n elements, n-1 iterations are
required to sort the array.
Pass 1
7 4 10 8 3 1
Sorted array
4 7 10 8 3 1
4 7 10 8 3 1
4 7 10 8 3 1
3 7 10 8 4 1
1 7 10 8 4 3
Unsorted sub array
Pass 2
1 7 10 8 4 3
Sorted array
1 7 10 8 4 3
1 7 10 8 4 3
1 4 10 8 7 3
1 3 10 8 7 4
Unsorted sub array
Pass 3
1 3 10 8 7 4
Sorted array
1 3 8 10 7 4
1 3 7 10 8 4
1 3 4 10 8 7
Sorted array Unsorted sub array
Pass 4
1 3 4 10 8 7
1 3 4 8 10 7
1 3 4 7 10 8
Pass 4 Sorted array Unsorted sub array
1 3 4 7 10 8
Sorted array
1 3 4 7 8 10
Coding
i=0
Main code:
For passes we execute loop
1 4 10 8 3 7
n-1
for(i=0;i<n-1;i++) i=1
{
1 3 10 8 4 7
int min=i;
for(j=i+1;j<n;j++)
{ i=2 1 3 4 8 10 7
if (a[j]<a[min])
min=j;
}
} i=3 1 3 4 7 10 8
If(min!=i)
{
swap(a[i[, a[min])
} i=4 1 3 4 7 8 10
Code
#include<iostream>
using namespace std;
void selectionSort(int arr[], int n) {
for (int i = 0; i < n - 1; i++) {
int min = i;
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[min]) {
min = j;
}
}
if (min != i) {
// Swap the elements
int temp = arr[i];
arr[i] = arr[min];
arr[min] = temp;
}
}
int main()
{
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr) / sizeof(arr[0]);
cout << "Original Array:"<<endl;
for (int i = 0; i < n; i++) {
cout << " " << arr[i];
}
cout << endl;
selectionSort(arr, n);