Selection Sort


selection sort

wikipedia

Algoritme ini pada setiap iterasinya memilih nilai paling kecil, diakhir iterasi nilai terkecil tersebut ditukar posisinya.

Contoh:

Misalkan kita punya data seperti ini: 6, 4, 3, 2 dan kita ingin mengurutkan data ini (ascending) dengan menggunakan selection sort. Berikut ini adalah proses yang terjadi:

Iterasi 1: data = 6, 4, 3, 2 minimum = 2 -> data = 2, 4, 3, 6

Iterasi 2: data = 2, 4, 3, 6 minimum = 3  -> data = 2, 3, 4, 6

Iterasi 3: data = 2, 3, 4, 6 minimum = 4  -> data = 2, 3, 4, 6

Berikut ini contoh programnya:

/*
  Name: Selection Sort
  Copyright: windupurnomo.wordpress.com@2009
  Author: Windu Purnomo
  Date: 15/12/09 17:18
  Description: Sample algorithm of sorting (ascending)
*/

#include<stdio.h>

void selectionSort(int data[], int n){
   int i, j=0, k=0, temp, min;
   for(i=0; i<n; i++){
      min = i;
      for(j=i+1; j<n; j++){
         if(data[min]>data[j])
            min = j;
      }
      temp = data[min];
      data[min] = data[i];
      data[i] = temp;
   }
}

main(){
   int data[1000];
   int n, i, j=0, k=0, temp, flag = 1;
   printf("________.:: SELECTION SORT ::.________\n");
   printf("Enter numbers of data(maks 1000): ");
   scanf("%d", &n);
   printf("Data (separate by space): ");
   for(i=0; i<n; i++)
      scanf("%d", &data[i]);

   selectionSort(data, n);

   printf("\nOutput after sort:\n");
   for(i=0; i<n; i++)
      printf("%d ", data[i]);

   getch();
   return 0;
}

About windupurnomo

I'm interested in programming. I am active with several programming such as Java, C #, C, JavaScript, HTML. I'm also develop desktop application (Java Swing), Mobile Application (Android), and Web programming (ASP MVC).
This entry was posted in C Language, programming and tagged , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s