Skip to content

Instantly share code, notes, and snippets.

@bytao7mao
Created August 9, 2017 21:53
Show Gist options
  • Save bytao7mao/bbe9aa7acdf429074487b0fdc017cfb9 to your computer and use it in GitHub Desktop.
Save bytao7mao/bbe9aa7acdf429074487b0fdc017cfb9 to your computer and use it in GitHub Desktop.
JAVA ascending algo
method #1:
public static void main(String[] args) {
int[] a = { 1, 4, 3, 5, 2 };
Arrays.sort(a);
System.out.println(Arrays.toString(a));
}
method #2:
public static int[] sortArray(int[] nonSortedArray) {
int[] sortedArray = new int[nonSortedArray.length];
int temp;
for (int j = 0; j < nonSortedArray.length - 1; j++) {// added this for loop, think about logic why do we have to add this to make it work
for (int i = 0; i < nonSortedArray.length - 1; i++) {
if (nonSortedArray[i] > nonSortedArray[i + 1]) {
temp = nonSortedArray[i];
nonSortedArray[i] = nonSortedArray[i + 1];
nonSortedArray[i + 1] = temp;
sortedArray = nonSortedArray;
}
}
}
return sortedArray;
}
method #3:
public static int[] sortArray(int[] nonSortedArray)
{
int[] sortedArray = new int[nonSortedArray.length];
int temp;
for (int i = 0; i <= nonSortedArray.length; i++)
{
for (int j = i+1; j < nonSortedArray.length; j++)
{
if (nonSortedArray[i] > nonSortedArray[j])
{
temp = nonSortedArray[i];
nonSortedArray[i] = nonSortedArray[j];
nonSortedArray[j] = temp;
sortedArray = nonSortedArray;
}
}
}
return sortedArray;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment