Skip to content

Instantly share code, notes, and snippets.

@prmichaelsen
Last active April 18, 2016 08:00
Show Gist options
  • Save prmichaelsen/c3dbb7e9e007362fb216a40b8bb20028 to your computer and use it in GitHub Desktop.
Save prmichaelsen/c3dbb7e9e007362fb216a40b8bb20028 to your computer and use it in GitHub Desktop.
/**
two var sort
by Patrick Michaelsen
[email protected]
[email protected]
[email protected]
A fun little code I made to see if I could sort an array with just two variables.
This algorithm has terrible time complexity. n^n to be exact.
**/
#include <stdio.h>
int main()
{
//i is index
//j is swap
int i = 0, j = 1;
int arr[10] = {5,9,1,4,7,8,6,3,2,0};
printf("%d\n",sizeof(arr)/sizeof(int));
int max = 50;
while ( j && max-- > 0 )
{
i = j = 0;
for( int k = 0; k < 10; k++ )
printf(" %d ",arr[k]);
printf("\n\n");
while ( i < (sizeof(arr)/sizeof(int)) - 1)
{
if ( arr[i] > arr[i+1] )
{
for( int k = 0; k < 10; k++ )
if( k == i || k == i+1 )
printf("[%d]",arr[k]);
else
printf(" %d ",arr[k]);
printf("\n");
for( int k = 0; k < 10; k++ )
if( k == i || k == i+1 )
printf(" V ");
else
printf(" ");
printf("\n");
j = arr[i];
arr[i] = arr[i+1];
arr[i+1] = j;
j = 1;
for( int k = 0; k < 10; k++ )
if( k == i || k == i+1 )
printf("[%d]",arr[k]);
else
printf(" %d ",arr[k]);
printf("\n");
}
i++;
}
}
printf("\n");
for( int k = 0; k < 10; k++ )
printf(" %d ",arr[k]);
printf("\n");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment