Minggu, 20 November 2011

Selection Sort Min and Max

  Agus Nur Ikhsan       Minggu, 20 November 2011
Change the selection sort (min) to min and max selection.

To find the minimum value and the place where found (index), we use the following methods:
void Sorting::minimum(int from, int n, int &temp) {
int min = data[from];
temp = from;
for (int i = from+1; i < n; i++)
if (data[i] < min)
{ min = data[i];
temp = i;

These methods used to find the smallest element of the array data from the position from up to n-1. The output is a place where the smallest element is found. We add a statement to look for the largest element and the place where the element was found.

we change the methods to be:
void Sorting::min_max(int from, int n, int &temp_min, int &temp_max) {
int min = data[from];
int max = data[from];
temp_min = from;
temp_max = from;
for (int i = from+1; i < n; i++) {
if (data[i] < min)
{ min = data[i];
temp_min = i;
if (data[i] > max)
{ max = data[i];
temp_max = i;

Thus, we change selection_sort methods following :

void Sorting::selection_sort(){
int t;
for (int i = 0; i
minimum(i, n, t);
swap(data[i], data[t]);
to be :
void Sorting::selection_sort_min_max() {
int left, right;
for (int i = 0; i < n/2; i++) {
min_max(i, n-i, left, right);
swap(data[i], data[left]);
swap(data[n-i-1], data[right]);

Thanks for reading Selection Sort Min and Max

« Prev Post

Tidak ada komentar:

Posting Komentar