Created
December 18, 2014 15:55
-
-
Save soltrinox/e145d05824a3557afb0c to your computer and use it in GitHub Desktop.
Gnome Sort
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static int[] gnomeSort(int[] nums){ //takes unsorted array, returns sorted | |
int index=1; //start of search | |
int temp; | |
while(index<nums.length){ //until the array is fully sorted | |
if(nums[index]<nums[index-1]){ //compares nums[index] with nums[index-1]. if smaller, switch. | |
temp=nums[index]; | |
nums[index]=nums[index-1]; | |
nums[index-1]=temp; | |
index--; //must decrease index to recheck. since they have been swapped, the array may still be out of order | |
if(index==0){ //prevents index from going lower than 1 | |
index=1; | |
} | |
} | |
else{ | |
index++; //if sorted, go up | |
} | |
} | |
return(nums); //reaching the end of the array- completely sorted, returns nums | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment