Sunday, September 26, 2010

isSorted() algorithm

This is just a simple program that checks to see if an input list of (n) size is sorted in ascending order. It really doesn't matter how many elements are in the list because the algorithm has to check every element to determine if the list is actually sorted. There is an if statement for the last element, because you don't have to compare it to the next term in the list (as there is none, it would generate an error). Therefore, when it reaches the last element, it will return true and leave the loop.

If even one number in the list is greater than its next element, it will display that the list is indeed not sorted, and break from the loop because there is no further need to check the rest of the list.

For example, say a list of [1, 2, 4, 3] is entered. The loop would go through once, see that 1 is < 2, and then move on to 2 and 4. It would also say that 2 < 4, and then would compare the last two numbers. Because 4 is not less than 3, it would return a statement saying the list is not sorted and the program would terminate.


You could use the same numbers and put them in as [4, 1, 2, 3]. It would compare the first 2 numbers and because 4 is greater than 1, the program would return the correct statement saying the list is not sorted and the program would also terminate.
import java.util.Scanner;


public class SortCheck
{


public static void main(String[] args)
{

int i = 0;
int j = 0;
boolean isComplete = false;
Scanner scan = new Scanner(System.in);
System.out.println("How many numbers are in the list?");
int numberOfItems = scan.nextInt();
int[] list = new int[numberOfItems];
int numbersInput = numberOfItems;
//Input all the numbers into the array
while(numberOfItems > 0)
{
System.out.println("Enter a number.");
int aNumber = scan.nextInt();
list[i] = aNumber;
i++;
numberOfItems--;
}
// ASCENDING SORT CHECK
while(isComplete == false)
{

//Determines if it has reached the end of the list yet. If it has reached the end,
//it has already checked if each element is higher than its preceding entry.
if(j==numbersInput-1)
{
System.out.println("This list is sorted.");
isComplete = true;
}
else
{
//If the element is less than the next entry, it simply increments the counter
//and goes to the next one.
if(list[j] < list[j+1])
{
j++;
}
//If any element does not fulfill the condition, it will break because there is
//no need to check the rest of the numbers.
else
{
System.out.println("This list is not sorted.");
isComplete = true;
}
}
}


}

}

No comments:

Post a Comment