Name: ____________________________________________________ Alpha: _____________________
Describe help received: _________________________________________________________________
What confuses me: Key points:
ints from the user and prints them into order so that all the odd
numbers come first (in increasing size) followed by all the even numbers (in
increasing size).
#include <iostream>
using namespace std;
void selectionsort(int* A, int N);
int indexOfMax(int* A, int N);
void swap(int& a, int& b);
bool before(int a, int b);
int main() {
int* A = new int[10];
for( int i=0; i < 10; i++ )
cin >> A[i];
selectionsort(A, 10);
for( int i=0; i < 10; i++ )
cout << A[i] << " ";
cout << endl;
return 0;
}
void selectionsort(int *A, int N) {
for( int length = N; length > 1; length-- ) {
int k = indexOfMax(A,length);
swap(A[k], A[length-1]);
}
}
int indexOfMax(int *A, int N) {
int imax = 0, i;
for( i = 1; i < N; i++ )
if( before(A[imax],A[i]) )
imax = i;
return imax;
}
void swap(int& a, int& b){ int t = b; b = a; a = t; }
// TO DO: define function before()
An example run:
~/$ ./hw
18 2 7 14 29 3 5 8 16 11
3 5 7 11 29 2 8 14 16 18
Complete the code so that it works correctly.
Turn In a screen capture of your program running on the above input, and a printout of your source code.
indexOfMin() is given a pointer A to an array and
returns the index of the element with the
minimum value among A[start], A[start+1], ..., A[end].
We are going to implement a different way of sorting numbers using
indexOfMin().
#include <iostream>
using namespace std;
int indexOfMin(int *A, int start, int end);
void sort(int* A, int N);
void swap(int& a, int& b);
int main() {
int* A = new int[5];
A[0] = 1; A[1] = 7; A[2] = 3; A[3] = 5; A[4] = 10;
sort(A, 5);
for( int i=0; i < 5; i++ )
cout << A[i] << " ";
cout << endl;
return 0;
}
int indexOfMin(int *A, int start, int end) {
int imin = start;
for( int i = start+1; i <= end; i++ )
if( A[imin] > A[i] )
imin = i;
return imin;
}
void swap(int& a, int& b){ int t = b; b = a; a = t; }
// TO DO: define function sort()
Complete the code so that it works correctly. Obviously, the program should output:
~/$ ./a.out
1 3 5 7 10
Note: Your function must use indexOfMin(). Don't create and use indexOfMax().
Turn In a screen capture of your program running on the above input, and a printout of your source code.