Berikut adalah source code C untuk Insertion Sort
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int main()
{
int loop, i, j, sort[100], temp;
printf("Masukkan jumlah data\n> ");
scanf("%d", &loop);
srand (time(NULL));
for (i=0; i<loop; i++)
{
sort[i] = rand();
}
for (i=1; i<loop; i++)
{
temp = sort[i];
j=i-1;
while (temp<sort[j] && j>=0)
{
sort[j+1] = sort[j];
j--;
}
sort[j+1] = temp;
}
printf("Hasil sorting\n> ");
for (i=0; i<loop; i++)
{
printf("%d ", sort[i]);
}
printf("\n");
}
Berikut adalah source code C untuk Merge Sort
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void mergesort(int[], int, int, int);
void partition(int[], int, int);
int main(){
int loop, sort[100], i;
printf("Masukkan jumlah data\n> ");
scanf("%d",&loop);
srand(time(NULL));
for(i=0; i<loop; i++)
{
sort[i] = rand() % 1000;
}
partition(sort, 0, loop-1);
printf("Hasil sorting\n> ");
for(i=0; i<loop; i++)
{
printf("%d ", sort[i]);
}
}
void partition(int sort[], int low, int high)
{
int mid;
if(low<high)
{
mid = (low + high) / 2;
partition (sort, low, mid);
partition (sort, mid + 1, high);
mergesort (sort, low, mid, high);
}
}
void mergesort(int sort[], int low, int mid, int high)
{
int i, m, k, l, temp[100];
l = low;
i = low;
m = mid + 1;
while((l <= mid) && (m <= high))
{
if(sort[l] <= sort[m])
{
temp[i] = sort[l];
l++;
}
else
{
temp[i] = sort[m];
m++;
}
i++;
}
if(l>mid)
{
for(k = m; k <= high ; k++)
{
temp[i] = sort[k];
i++;
}
}
else
{
for(k=l; k <= mid; k++)
{
temp[i] = sort[k];
i++;
}
}
for(k = low; k <= high; k++)
{
sort[k]=temp[k];
}
}
Berikut adalah source code C untuk Quick Sort
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void quicksort (int[], int, int);
int main()
{
int loop, sort[100], i;
printf("Masukkan jumlah data\n> ");
scanf("%d", &loop);
srand (time(NULL));
for(i=0; i<loop; i++)
{
sort[i] = rand() % 100;
}
quicksort (sort, 0, loop-1);
printf("Hasil sorting\n> ");
for(i=0; i<loop; i++)
{
printf("%d ", sort[i]);
}
}
void quicksort (int sort[], int first, int last)
{
int mid, i, j, temp;
if(first<last)
{
mid = first;
i = first;
j = last;
while (i<j)
{
while (sort[i] <= sort[mid] && i < last) i++;
while (sort[j] > sort[mid]) j--;
if (i<j)
{
temp = sort[i];
sort[i] = sort[j];
sort[j] = temp;
}
}
temp = sort[mid];
sort[mid] = sort[j];
sort[j] = temp;
quicksort (sort, first, j-1);
quicksort (sort, j+1, last);
}
}
Berikut adalah source code C untuk Selection Sort
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int loop, i, j, temp, sort[100];
printf("Masukkan jumlah data\n> ");
scanf("%d", &loop);
srand(time(NULL));
for (i=0; i<loop; i++)
{
sort[i] = rand();
}
for(i=0; i<loop; i++)
{
for (j=i+1; j<loop; j++)
{
if (sort[i] > sort[j])
{
temp = sort[i];
sort[i] = sort[j];
sort[j] = temp;
}
}
}
printf("Hasil sorting\n> ");
for(i=0; i<loop; i++)
{
printf("%d ", sort[i]);
}
}
Tidak ada komentar:
Posting Komentar