Skip to content

Instantly share code, notes, and snippets.

@aggrolite
Created April 6, 2011 18:21
Show Gist options
  • Save aggrolite/906207 to your computer and use it in GitHub Desktop.
Save aggrolite/906207 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include "sort.h"
#define SIZE 10 //size of the array we're dealing with
//function to scramble the array after we've sorted it
void Rearrange(int *ptr)
{
}
//after we've sorted, we'll use this function to print it out all pretty
void PrettyPrint(int *ptr)
{
int i; //index var
printf("Sorted: ");
for(i=0;i<SIZE;i++) //loop thru array
{
printf("%d ",ptr[i]); //print each one out
}
printf("\n"); //new line
}
int main(void)
{
int list[SIZE]={5,1,2,8,9,7,3,4,10,6};
int *listPtr=NULL; //initialize the list's pointer
listPtr=&list[0]; //set the pointer to index 0 of the list
Bubble(listPtr,SIZE); //now let's do Bubble Sort. this function will alter the array we've defined in main
PrettyPrint(listPtr); //and let's show the sorted array to the user
return 0;
}
//just a swap function to switch two items in the array
void Swap(int *ptr, int i)
{
/*
Let's swap it without a 3rd variable since we're dealing with numbers...
a=a+b
b=a-b
a=a-b
*/
ptr[i-1] += ptr[i];
ptr[i] = ptr[i-1] - ptr[i];
ptr[i-1] = ptr[i-1] - ptr[i];
}
void Bubble(int *list, int size)
{
int i; //index var
int swapped;
do {
swapped=0;
for(i=1;i<size;i++) //loop thru array
{
if (list[i-1] > list[i]) //if the previous item is larger than our current item, we need to swap
{
Swap(list,i); //pass these two val
swapped=1;
}
}
} while (swapped);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment