# #include <stdio.h> #include <conio.h> #include <stdlib.h> #define MAX 100 #define INPUT 'i' #define OUTPUT 'o' #define _MY_DEBUG #if defined(_MY_DEBUG) #define TRACE_LINE printf("\n\n- Program Statistics :\n1. File : %s\n2. Date : %s\n3. Time : %s\n",__FILE__,__DATE__,__TIME__); #else #define TRACE_LINE #endif // int CheckForBadSorting(int*, const int); void ShellSortPass(int*, const int, const int); void ShellSort(int*, const int); void InputOutput(int*, const int, const char); void FreeBuffer(int*); int main(int argc, char* argv[]) { system("COLOR 5"); int *buffer = NULL, max; printf("Implementasi Shell Sort\nMasukkan jumlah data [MAX:100] : "); scanf("%d",&max); fflush(stdin); if((max > 0) && (max <= MAX)) { buffer = (int*)calloc(max,sizeof(int)); InputOutput(buffer,max,INPUT); printf("\nData yang anda masukkan : "); InputOutput(buffer,max,OUTPUT); ShellSort(buffer,max); printf("\nData setelah disorting : "); InputOutput(buffer,max,OUTPUT); FreeBuffer(buffer); /* if(CheckForBadSorting(buffer,max)) { goto MARK; } else { InputOutput(buffer,max,OUTPUT); } */ } /* MARK : if(buffer != NULL) { FreeBuffer(buffer); } */ TRACE_LINE; getch(); fflush(stdin); return(EXIT_SUCCESS); } /* int CheckForBadSorting(int* buffer, const int max) { int i; for(i = 1; i < max; ++i) { if(buffer[i-1] > buffer[i]) { printf("Bad Sorting!"); return(1); } } return(0); } */ void ShellSortPass(int* buffer, const int max, const int interval) { int i; for(i = 0; i < max; ++i) { int j, tmp = buffer[i]; for(j = i-interval; j >= 0; j -= interval) { if(buffer[j] <= tmp) { break; } buffer[j+interval] = buffer[j]; } buffer[j+interval] = tmp; } } void ShellSort(int* buffer, const int max) { int CiuraIntervals[] = {701, 301, 132, 57, 23, 10, 4, 1}, IntervalIdx = 0, interval = CiuraIntervals[0]; double ExtendCiuraMultiplier = 2.3; if(max > interval) { while(max > interval) { --IntervalIdx; interval = (int)(interval*ExtendCiuraMultiplier); } } else { while(max < interval) { ++IntervalIdx; interval = CiuraIntervals[IntervalIdx]; } } while(interval > 1) { ++IntervalIdx; if(IntervalIdx >= 0) { interval = CiuraIntervals[IntervalIdx]; } else { interval = (int)(interval/ExtendCiuraMultiplier); } ShellSortPass(buffer,max,interval); } } void InputOutput(int* buffer, const int max, const char STAT) { int i; if('i' == STAT) { for(i = 0; i < max; ++i) { printf("%d. Data ke-%d : ",(i+1),(i+1)); scanf("%d",&buffer[i]); fflush(stdin); } } else if('o' == STAT) { for(i = 0; i < max; ++i) { printf("%d ",buffer[i]); } } } void FreeBuffer(int* buffer) { free(buffer); buffer = NULL; }
Tuesday, November 29, 2011
Shell Sort dalam bahasa C
Subscribe to:
Post Comments (Atom)
Artikelnya menarik kak, ini saya juga punya artikel tentang Bubble Sort, semoga dapat saling melengkapi
ReplyDeleteBubble Sort dalam Bahasa C (Materi + Koding)