Permalink
Browse files

Add bubblesort, insertionsort, and selectionsort

  • Loading branch information...
kapcino committed Jan 4, 2012
1 parent a753d3d commit 1b207e9bdbfa8c519bb898e697e04f194f9fa728
Showing with 117 additions and 1 deletion.
  1. +1 −1 Makefile
  2. +30 −0 bubblesort.c
  3. +37 −0 insertionsort.c
  4. +37 −0 selectionsort.c
  5. +12 −0 util.h
View
@@ -1,7 +1,7 @@
CFLAGS=-Wall -ansi
.PHONY: all clean
-all: quickfind mergesort reverselinklist stack_array
+all: quickfind mergesort reverselinklist stack_array insertionsort bubblesort selectionsort
clean:
rm *.exe
View
@@ -0,0 +1,30 @@
+#include "util.h"
+
+void bubblesort(int a[], int len)
+{
+ int i=-1;
+ int j=-1;
+ int tmp=-1;
+ for(i=0; i<len; i++)
+ {
+ for(j=i+1; j<len; j++)
+ {
+ if(a[j]<a[j-1])
+ {
+ tmp=a[j];
+ a[j]=a[j-1];
+ a[j-1]=tmp;
+ }
+ }
+ }
+}
+
+int main(int argc, char* argv[])
+{
+ int a[10] = {0, 3, -1, -4, 6, 9, 3, 0, 2, -7};
+ print(a, 10);
+ bubblesort(a, 10);
+ print(a, 10);
+
+ return 0;
+}
View
@@ -0,0 +1,37 @@
+#include <stdio.h>
+
+void insertionsort(int a[], int len)
+{
+ int tmp = -1;
+ int i = 1;
+ int j = -1;
+ for(i=1; i<len; ++i)
+ {
+ for(j=i; j>0 && a[j]<a[j-1]; j--)
+ {
+ tmp=a[j];
+ a[j]=a[j-1];
+ a[j-1]=tmp;
+ }
+ }
+}
+
+void print(int a[], int len)
+{
+ int i;
+ for(i=0; i<len; ++i)
+ {
+ printf("%d ", a[i]);
+ }
+ printf("\n");
+}
+
+
+int main(int argc, char* argv[])
+{
+ int a[] = {1, 4, -6, 3, -8, 6 ,4};
+ print(a, 7);
+ insertionsort(a,7);
+ print(a, 7);
+ return 0;
+}
View
@@ -0,0 +1,37 @@
+#include "util.h"
+
+void selectionsort(int a[], int len)
+{
+ int i;
+ int j;
+ int tmp;
+ int mini;
+
+ for(i=0; i<len; ++i)
+ {
+ mini=i;
+ for(j=i+1; j<len; j++)
+ {
+ if(a[j]<a[mini])
+ {
+ mini=j;
+ }
+ }
+ if(mini != i)
+ {
+ tmp=a[i];
+ a[i]=a[mini];
+ a[mini]=tmp;
+ }
+ }
+
+}
+
+int main(int argc, char* argv[])
+{
+ int a[10] = {4, 9, 0, 6, 3, -4, 1, 9, 4, 20};
+ print(a, 10);
+ selectionsort(a, 10);
+ print(a, 10);
+ return 0;
+}
View
12 util.h
@@ -0,0 +1,12 @@
+#include <stdio.h>
+
+
+void print(int a[], int len)
+{
+ int i;
+ for(i=0; i<len; ++i)
+ {
+ printf("%d ", a[i]);
+ }
+ printf("\n");
+}

0 comments on commit 1b207e9

Please sign in to comment.