
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Sort an Array of Strings Using Selection Sort in C++
The Selection Sort algorithm sorts an exhibit by more than once finding the base component from the unsorted part and putting it toward the start. In each emphasis of determination sort, the base component from the unsorted subarray is picked and moved to the arranged subarray.
Example
#include <iostream> #include <string.h> using namespace std; #define MAX_LEN 50 void selectionSort(char arr[][50], int n){ int i, j, mIndex; // Move boundary of unsorted subarray one by one char minStr[50]; for (i = 0; i < n-1; i++){ // Determine minimum element in unsorted array int mIndex = i; strcpy(minStr, arr[i]); for (j = i + 1; j < n; j++){ // check whether the min is greater than arr[j] if (strcmp(minStr, arr[j]) > 0){ // Make arr[j] as minStr and update min_idx strcpy(minStr, arr[j]); mIndex = j; } } // Swap the minimum with the first element if (mIndex != i){ char temp[50]; strcpy(temp, arr[i]); //swap item[pos] and item[i] strcpy(arr[i], arr[mIndex]); strcpy(arr[mIndex], temp); } } } int main(){ char arr[][50] = {"Tom", "Boyaka", "Matt" ,"Luke"}; int n = sizeof(arr)/sizeof(arr[0]); int i; cout<<"Given String is:: Tom, Boyaka, Matt, Luke\n"; selectionSort(arr, n); cout << "\nSelection Sorted is::\n"; for (i = 0; i < n; i++) cout << i << ": " << arr[i] << endl; return 0; }
This above C++ program initially chooses the smallest component in the exhibit and swaps it with the principal component in the cluster. Next, it swaps the second littlest component in the cluster with the subsequent component, etc. In this manner for each pass, the smallest component in the exhibit is chosen and put in its legitimate situation until the whole cluster is arranged. Finally, the section sort method sorts the given string in ascending order as follows;
Output
Given string is:: Tom, Boyaka, Matt, Luke Selection Sorted:: Boyaka Luke Matt Tom
Advertisements