I'm a novice and started diving into data structures and algorithms recently. I was taught bubble sort recently and I found that the original bubble sort algorithm is so inefficient, so I wrote a modified, yet simple version of it.
Algorithm:
- Loop through the provided array and store the index of the max element
- Swap the last element with the max element
- Decrease the total looping length by 1 and repeat
Code:
import java.util.Scanner;
class Methods extends Main
{
int[] getArray(int len)
{
int[] array = new int[len];
for (int i = 0; i < array.length; i++)
{
array[i] = sc.nextInt();
}
return array;
}
int [] pushMaxSort(int[] arr)
{
int len = arr.length;
while (len>0)
{
int max=arr[0];
int index=0;
for(int i=0; i<len;i++)
{
if(arr[i]>max)
{
max = arr[i];
index = i;
}
}
int temp = arr[len-1];
arr[len-1] = arr[index];
arr[index] = temp;
len--;
}
return arr;
}
void printArr(int []arr)
{
System.out.println("sorted array :");
for(int i=0;i<arr.length;i++)
{
System.out.print("\t" +arr[i]);
}
}
}
class Main
{
static Scanner sc = new Scanner(System.in);
public static void main(String[] args)
{
long t = System.currentTimeMillis();
Methods o = new Methods();
o.printArr(o.pushMaxSort(o.getArray(sc.nextInt())));
long t2 = System.currentTimeMillis();
System.out.println("\n\n time " + (t2-t));
}
}
Also, I need to learn to describe complexity (using Big O notation). I am vaguely guessing this has \$O(n \log{n})\$ but please let me know of the exact running time.