0
String program using selection sort
???????
2 Réponses
+ 2
/*
One of the simplest techniques is a selection sort. As the name suggests, selection sort is the selection of an element
and keeping it in sorted order. In selection sort, the strategy is to find the smallest number in the array and exchange
it with the value in first position of array. Now, find the second smallest element in the remainder of array and exchange
it with a value in the second position, carry on till you have reached the end of array. Now all the elements have been
sorted in ascending order.
Selection Sort Algorithm
-------------------------
Let ARR is an array having N elements
1. Read ARR
2. Repeat step 3 to 6 for I=0 to N-1
3. Set MIN=ARR[I] and Set LOC=I
4. Repeat step 5 for J=I+1 to N
5. If MIN>ARR[J], then
(a) Set MIN=ARR[J]
(b) Set LOC=J
End if
[End of step 4 loop]
6. Interchange ARR[I] and ARR[LOC] using temporary variable
[End of step 2 outer loop]
7. Exit
*/
#include<iostream>
#include<string.h>
#include<stdio.h>
using namespace std;
int main(){
int i,j,n,loc;
string a[30],temp,min;
cout<<"Enter the number of elements:";
cin>>n;
cout<<"\nEnter the elements\n";
for(i=0;i<n;i++){
cin>>a[i];
}
for(i=0;i<n-1;i++){
min=a[i];
loc=i;
for(j=i+1;j<n;j++){
if(min>a[j]){
min=a[j];
loc=j;
}
}
temp=a[i];
a[i]=a[loc];
a[loc]=temp;
}
cout<<"\nSorted list is as follows\n";
for(i=0;i<n;i++){
cout<<a[i]<<"\n";
}
return 0;
}
- 1
Please tell the program answer