This c++ program sort an array
using selection sort.
C++ Program for Selection Sort
#include<iostream>
using namespace std;
int main()
{
int size;
cout<<"Enter
the size of array: ";
cin>>size;
int arr[size], i, j,
temp;
cout<<"\nEnter
the array elements: ";
for(i=0; i<size; i++)
cin>>arr[i];
/*Sorting Array Using
Selection Sort*/
for(i=0; i<size; i++)
for(j=i+1;
j<size; j++)
if(arr[i]>arr[j])
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
cout<<"\nArray
in ascending order: ";
for(i=0; i<size; i++)
cout<<arr[i]<<" ";
return 0;
}
OUTPUT:
Enter the size of array: 5
Enter the array elements: 9 5 3 8 4
Array in ascending order: 3 4
5 8 9
C++ Program for Selection Sort Using
Class
#include<iostream>
using namespace std;
class SelctionSort
{
private:
int arr[50];
int size;
public:
SelctionSort(int s)
{
size = s;
}
void setElements()
{
int i;
cout<<"Enter the array elements: ";
for(i=0;
i<size; i++)
cin>>arr[i];
}
void sortArray()
{
int i, j,
temp;
for(i=0;
i<size; i++)
for(j=i+1; j<size; j++)
if(arr[i]>arr[j])
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
void displayArray()
{
int i, j;
/*Sorting
Array Using Selection Sort*/
cout<<"\nArray in ascending order: ";
for(i=0;
i<size; i++)
cout<<arr[i]<<" ";
}
};
int main()
{
int size;
cout<<"Enter
the size of array: ";
cin>>size;
SelctionSort a(size);
a.setElements();
a.sortArray();
a.displayArray();
return 0;
}
OUTPUT:
Enter the size of array: 5
Enter the array elements: 8 9 4 6 2
Array in ascending order: 2 4
6 8 9
0 comments:
Post a Comment