C++ program to implement Selection Sort:
#include
using namespace std;
void swap(int &a, int &b)
{
int temp;
temp = a;
a = b;
b = temp;
}
void display(int *array, int size)
{
for(int i = 0; i cout << array[i] << " ";
cout << endl;
}
void selectionSort(int *array, int size)
{
int i, j, k;
for(i = 0; i {
k = i;
for(j = i+1; j if(array[j] < array[k])
k = j;
swap(array[i], array[k]);
}
}
int main()
{
int n;
cout << "Enter the number of elements: ";
cin >> n;
int arr[n];
cout << "Enter elements:" << endl;
for(int i = 0; i {
cin >> arr[i];
}
cout << "Array before Sorting: ";
display(arr, n);
selectionSort(arr, n);
cout << "Array after Sorting: ";
display(arr, n);
}
Output
Enter the number of elements: 4
Enter elements:
5 9 7 23
Array before Sorting: 5 9 7 23
Array after Sorting: 5 7 9 23
#include
using namespace std;
void swap(int &a, int &b)
{
int temp;
temp = a;
a = b;
b = temp;
}
void display(int *array, int size)
{
for(int i = 0; i
cout << endl;
}
void selectionSort(int *array, int size)
{
int i, j, k;
for(i = 0; i
k = i;
for(j = i+1; j
k = j;
swap(array[i], array[k]);
}
}
int main()
{
int n;
cout << "Enter the number of elements: ";
cin >> n;
int arr[n];
cout << "Enter elements:" << endl;
for(int i = 0; i
cin >> arr[i];
}
cout << "Array before Sorting: ";
display(arr, n);
selectionSort(arr, n);
cout << "Array after Sorting: ";
display(arr, n);
}
Output
Enter the number of elements: 4
Enter elements:
5 9 7 23
Array before Sorting: 5 9 7 23
Array after Sorting: 5 7 9 23
No comments:
Post a Comment