Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

updated the necessary change #117

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
79 changes: 52 additions & 27 deletions cpp/SelectionSort.cpp
Original file line number Diff line number Diff line change
@@ -1,31 +1,56 @@
#include <bits/stdc++.h>
#include <stdio.h>
#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
#include <cmath>
#include <cstring>

using namespace std;
const int ARRAY_SIZE = 7;

void selectionSort(int list[], int length);

int main()
{
int n,i,j,minIndex,t;
cin>>n;
int a[n];
for (i=0;i<n;i++)
{
cin>>a[i];
}
for (i=0;i<n-1;i++)
{
minIndex=i;
for(j=i;j<n;j++)
{
if(a[j] < a[minIndex])
minIndex=j;
}
t=a[i];
a[i]=a[minIndex];
a[minIndex]=t;
}
for (i=0;i<n;i++)
{
cout<<a[i]<<" ";
}

return 0;
int i;
int arr[] = { 35, 12, 27, 18, 45, 16, 38 };

cout << "The unsorted list is: ";

for (i = 0; i < ARRAY_SIZE; i++) {
cout << arr[i] << " ";
}
cout << endl;

selectionSort(arr, ARRAY_SIZE);

cout << "The sorted list is: ";

for (i = 0; i < ARRAY_SIZE; i++) {
cout << arr[i] << " ";
}
cout << endl;

return 0;
}

void selectionSort(int list[], int length) {
int index;
int smallestIndex;
int location;
int temp;

for (index = 0; index < length - 1; index++) {
// step a (find smallest element)
smallestIndex = index;
for (location = index + 1; location < length; location++) {
if (list[location] < list[smallestIndex]) {
smallestIndex = location;
}
}
// step b (swap elements)
temp = list[smallestIndex];
list[smallestIndex] = list[index];
list[index] = temp;
}
}