Turbo Sort (Beginner)

import java.util.Scanner;

class code {

public static void main(String args[])
{
	Scanner scan = new Scanner(System.in);
	Integer testCases = scan.nextInt();
	Integer list[] = new Integer[testCases];
	if(testCases<=1000000)
	{
		for (int i = 0; i < testCases; i++) 
		{
			Integer number = scan.nextInt();
			if(number>=0 && number<=1000000)
			{
				list[i]=number;
			}
		}
		for (int i = 1; i < list.length; i++) {
			Integer key= list[i];
			Integer j = i-1;
			while(j>=0 && list[j]>key)
			{
				list[j+1]=list[j];
				j = j-1;
			}
			list[j+1]=key;
		}
		for (int i = 0; i < list.length; i++) {
			System.out.println(list[i]);
		}
	}
	
}

}

I am still getting “Time limit exceed” error. Anyone facing the same problem?

You could use the Arrays.sort() from java.util.Arrays library. This sorts the array in ascending order.
You may also check out my solution, but I would encourage you to try it out using Arrays.sort() first!:

https://www.codechef.com/viewsolution/15415924

If you find this solution helpful, please upvote and accept this as the answer! :slight_smile:

Hey i think you should learn merge sort, quick sort and other good sorting algorithm.

1 Like

what about collections? Can we use similar functions in ArrayList. I checked but didn’t find any!

what’s the issue with insertion sort?

Yes, ArrayList.sort exists. There is also the more general Collections.sort which works for any Collection.

The inputs are guaranteed to obey the constraints so you do not need to verify them.

@bajasahay insertion sort has a time complexity of \mathcal{O}(n^2) but there exist more efficient sorting algorithms such as mergesort or quicksort which work in \mathcal{O}(n \log n).

//