CSE 100 Lecture Notes - Lecture 41: Selection Sort

93 views3 pages
Sample Code for Examples in Chapter 9:
#include <iostream>
using namespace std;
int main()
{
int array1[] = {10, 5, 6, 17, 9, 20};
const int SIZE = 6;
cout<<"The original array is ";
for(int i = 0; i< SIZE; i++)
{
cout<< array1[i]<<", ";
}
cout<<endl<<endl;
//selection sort algorithm
for(int i = 0; i < SIZE; i++)
{
//find the smallest value's subscript
int index=-1;
int smallest = 10000;
for(int j = i; j<SIZE; j++)
{
if(array1[j]<smallest)
{
smallest = array1[j];
index = j;
}
}
//Exchange the values of ith position and the smallest value
int temp = array1[i];
array1[i] = array1[index];
array1[index] = temp;
}
//Display the sorted array
cout<<"The sorted array is ";
for(int i = 0; i< SIZE; i++)
{
Unlock document

This preview shows page 1 of the document.
Unlock all 3 pages and 3 million more documents.

Already have an account? Log in

Get access

Grade+
$40 USD/m
Billed monthly
Grade+
Homework Help
Study Guides
Textbook Solutions
Class Notes
Textbook Notes
Booster Class
10 Verified Answers
Class+
$30 USD/m
Billed monthly
Class+
Homework Help
Study Guides
Textbook Solutions
Class Notes
Textbook Notes
Booster Class
7 Verified Answers

Related Documents

Related Questions