Wager Mage
Photo by Miguel Á. Padriñán Pexels Logo Photo: Miguel Á. Padriñán

Which algo finds largest number first?

In a selection sort, the first process in the algorithm is to find the data element that has the largest value.

How do I BetOnline in a state that doesn't allow it?
How do I BetOnline in a state that doesn't allow it?

If you live in a state where online gambling is not yet regulated, then you have the option of using a VPN. This tool will change your IP address...

Read More »
How do I BetOnline in Zambia?
How do I BetOnline in Zambia?

The most popular sports betting sites in Zambia are primarily betPawa, Betway, CaslteBet, BolaBet and bet365. These sites are trusted by several...

Read More »

Sorting

There are many situations that required data to be sorted in some type of order. When it comes to sorting algorithms, a simple way to categorize them is that the simplest algorithms are usually the slowest and the algorithms that result in the fastest sorting tends to be complex to understand. A more accurate view of how sorting algorithms could be categorized is that the algorithms that arrange the data in a way that allows less comparisons to take place tends to result in faster sorts. This arranging of data that allows less comparisons is what generally makes those algorithms more complex.

Computer sorting versus Human sorting

Humans and computers do not sort things the same way. This is mainly because humans can consider more than two data values at once, whereas a computer can only compare two data values at a time. The other reason for the difference is that a computer handles large amounts of data better than a human can. The most common reason for students having difficulty with writing and implementing sorting algorithms is that they don't take into account the fact that the computer can only compare two data values at a time. Thus, a computer sorting algorithm is different from the one a human might use at first glance.

Selection sort

The selection sort is based on one of the simpler sorting algorithms. It is a relatively slow sort, but it is a good example of using repetition and selection statements. Suppose you have the following numbers in an array: You want to sort these numbers. As a human you could probably do this in your head. But, the computer can only look at two of these values at a time. In a selection sort, the first process in the algorithm is to find the data element that has the largest value.

Finding the max value

In finding the maximum value, you have to take into account the fact that the computer can only deal with at most two elements at a time. So, the computer could look at the first two elements for example. Actually, to find the maximum value, we want to keep track of both the value of the maximum and the position of that maximum. To do this, we will arbitrarily set the first element to be the maximum value. The following illustrates what we have at this point.

Now, let's look at the next position:

We check to see if the value at this position is larger than max. If it is, then the value becomes the new value for max, and the position becomes the new maxpos. In this case, 23 is not larger than 43, so max and maxpos are left alone. Let's look at the next position. In this case, 55 is larger than 43, so max is updated to 55, and maxpos is updated to 2. Let's continue: Since 16 is not greater than 55, max and maxpos are left alone and we go to the next position. Again, 29 is not greater than 55 so max and maxpos are left alone and we go to the next position. Since 5 is not larger than 55, max and maxpos are left alone. We just reached the end of the array, so we have found the maximum value and its position.

Swap the max value into the lead position

Now that we have found the maximum value, we want to swap the maximum value with the value in the lead position (element zero in this case). Such a swap is accomplished in two steps. First, the value from the lead position is copied into the position given by maxpos.

Then, the max value is copied into the lead position.

At this point the array looks like this:

The process is repeated by changing the lead position to be the second element. The overall process is repeated until the array is sorted. A simple algorithm for this process would be: 1. Set pos to zero 2. Find max and maxpos of array going from pos to end of array 3. Swap values in maxpos and pos 4. Increment pos 5. If pos < end of array repeat 1-4. Else end Let's put more details into this algorithm. We know that the process repeats itself until the second to the last array element is reached. So, this could be handled using a for loop. For each pos starting at zero up to second to last array element Set max to array[pos] Set maxpos to pos For each j from one more than the pos up to last array element If array[j] > max Set max to array[j] Set maxpos to j Set array[maxpos] to array[pos] Set array[pos] to max If we turned this into an actual Java program, this would look like: class Select { public static void main(String[] args) { int[] nums = {43,23,55,16,29,5}; for (int pos = 0; pos < nums.length-1; pos++) { int max = nums[pos]; int maxpos = pos; for (int j = pos+1; j < nums.length; j++) { if (nums[j] > max) { max = nums[j]; maxpos = j; } } nums[maxpos] = nums[pos]; nums[pos] = max; } // print out the sorted array for (int i = 0; i < nums.length; i++) { System.out.print(nums[i] + " "); } System.out.println(""); } } The last for loop is just used to print out the sorted array.

Insertion Sort

The insertion sort is similar to the kind of sorting you might do if you were trying to to put people in order from shortest to tallest. You get everyone to line up and you start with the left side. Starting with the second position from the left, you check to see if the person to the left is shorter. If this is true, move the person to the left. Then, you start with the third person from the left. That person is moved left until they are taller than person to the left of them. This process is repeated until the whole group is sorted. A simple algorithm for this would be: for person from second person to the last person while person is shorter than person to the left move position to the left

Why do tennis players drink from 2 bottles?
Why do tennis players drink from 2 bottles?

Most professional tennis players have two different drink bottles on the court. One contains water while the other is an electrolyte drink and / or...

Read More »
What games pay real money the same day?
What games pay real money the same day?

17 Best Cash App Games that Pay Real Money Swagbucks. There are several ways you can earn extra cash on Swagbucks, and one of the best ways is by...

Read More »

Changing this algorithm to use an array of numbers and adding more details would result in the following: For start = 1 up to start < length of array, start++ pos = start temp = array[pos] While pos > 0 and temp < array[pos - 1] array[pos] = array[pos - 1] pos-- array[pos] = temp

The following program shows this algorithm implemented as Java code.

class Insert { public static void main(String[] args) { int[] nums = {43,23,55,16,29,5}; for (int start = 1; start < nums.length; start++) { int pos = start; int temp = nums[pos]; while (pos > 0 && temp < nums[pos - 1]) { nums[pos] = nums[pos-1]; pos--; } nums[pos] = temp; } for (int j = 0; j < nums.length; j++) { System.out.print(nums[j] + " "); } System.out.println(""); } } Again, the last for loop is just to print out the sorted array.

Sorting reference types that implement Comparable

If you create a reference type that implements the Comparable interface, you will need to implement the compareTo() method. The compareTo() method uses the class' instance variables to make a comparison. The method returns an int that is positive if the object is greater than the passed object, negative if the object is less than the passed object and zero if the objects are equal. The advantage of making a reference type implement the Comparable interface, is that you can sort an array of this reference type by using java.util.Arrays.sort(). This is a very fast sort that takes into account things like if the array is already sorted and if the array has a lot of repeat values. Here is a simple example of a class that just wraps around an int and implements the Comparable interface: public class MyNumber implements Comparable { private int num; public MyNumber(int maxNum) { num = (int)(Math.random()*maxNum) + 1; } public MyNumber() { this(400); } public String toString() { return "num: " + num; } public int getNum() { return num; } public int compareTo(MyNumber n) { int temp = this.num - n.getNum(); return temp; } } Note the class header and how it specifies the type. This is the way to implement the Comparable interface taking into account generics. The compareTo() method is implemented on lines 15-18. All it does is subtract the instance variable parts of the objects to get the comparison. Note that this would not be good enough if negative values for num were allowed. But, in this case only positive numbers are allowed for num so this is okay. When you are trying to compare different kinds of sorts, it is useful to time the results within the program. Here is a class called Stopwatch that will make that easy to do. public class Stopwatch { private final long start; public Stopwatch() { start = System.currentTimeMillis(); } public double elapsedTime() { long now = System.currentTimeMillis(); return (now - start)/1000.0; } } Let's write a program that allows comparison of the Selection sort, the Insertion sort and Arrays.sort(). import java.util.Arrays; import java.util.Collections; class CompareSorts { public static void main(String[] args) { int size = 0; try { size = Integer.parseInt(args[0]); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Usage: java CompareSorts n"); System.out.println("where n is the size of the array"); System.exit(1); } MyNumber[] nums = new MyNumber[size]; for (int i = 0; i < nums.length; i++) { nums[i] = new MyNumber(100000); } // make copies MyNumber[] nums2 = new MyNumber[size]; MyNumber[] nums3 = new MyNumber[size]; MyNumber[] nums4 = new MyNumber[size]; for (int i = 0; i < nums.length; i++) { nums2[i] = nums[i]; nums3[i] = nums[i]; nums4[i] = nums[i]; } // Selection sort nums2 Stopwatch timer = new Stopwatch(); selectSort(nums2); System.out.println("Selection sort completed:"); System.out.println("elapsed time: " + timer.elapsedTime()); System.out.println("array sorted: " + isSorted(nums2)); //print(nums2); // Insertion sort nums3 timer = new Stopwatch(); insertionSort(nums3); System.out.println(" Insertion sort completed:"); System.out.println("elapsed time: " + timer.elapsedTime()); System.out.println("array sorted: " + isSorted(nums3)); // Arrays.sort(nums4) timer = new Stopwatch(); Arrays.sort(nums4,Collections.reverseOrder()); System.out.println(" Arrays.sort() completed:"); System.out.println("elapsed time: " + timer.elapsedTime()); System.out.println("array sorted: " + isSorted(nums4)); // sort sorted arrays timer = new Stopwatch(); selectSort(nums2); System.out.println(" Selection sort on sorted array:"); System.out.println("elapsed time: " + timer.elapsedTime()); System.out.println("array sorted: " + isSorted(nums2)); timer = new Stopwatch(); insertionSort(nums3); System.out.println(" Insertion sort on sorted array:"); System.out.println("elapsed time: " + timer.elapsedTime()); System.out.println("array sorted: " + isSorted(nums3)); timer = new Stopwatch(); Arrays.sort(nums4,Collections.reverseOrder()); System.out.println(" Arrays.sort() on sorted array:"); System.out.println("elapsed time: " + timer.elapsedTime()); System.out.println("array sorted: " + isSorted(nums4)); } // main ends private static void selectSort(MyNumber[] a) { for (int pos = 0; pos < a.length-1; pos++) { MyNumber max = a[pos]; int maxpos = pos; for (int j = pos+1; j < a.length; j++) { if (a[j].compareTo(max) > 0) { max = a[j]; maxpos = j; } } a[maxpos] = a[pos]; a[pos] = max; } } private static void insertionSort(MyNumber[] a) { for (int start = 1; start < a.length; start++) { int pos = start; MyNumber temp = a[start]; while (pos > 0 && temp.compareTo(a[pos-1]) > 0) { a[pos] = a[pos-1]; pos--; } a[pos] = temp; } } private static boolean isSorted(MyNumber[] a) { boolean sorted = true; for (int i = 0; i < a.length - 1; i++) { if (a[i].compareTo(a[i+1]) < 0) { sorted = false; break; } } return sorted; } private static void print(MyNumber[] a) { for (int i = 0; i < a.length; i++) { System.out.print(a[i].getNum() + " "); } System.out.println(""); } } Lines 6-13 define a try-catch block that attempts to use the argument from the command line to set the size of the arrays to sort. If no argument is supplied, the catch block prints a usage message and exits the program. This means that if you enter:

How does a minus money line work?
How does a minus money line work?

If you place a $100 bet at odds of +120 and that team goes on to win the game, your profit would be $120. Negative odds: When the odds are...

Read More »
What hands should you see the flop with?
What hands should you see the flop with?

Limping in. This will normally be when there have been a number of other players limping-in before you, and so you will have better odds to see a...

Read More »

java CompareSorts 100

this will create an array of 100 elements for sorting.

Lines 14-17 construct the array of type MyNumber and populate that array. The MyNumber constructor will generate objects with the num instance variable set randomly between 1 and the number passed as an argument. Lines 19-26 create three copies of the original array so that each sort is working on exactly the same array. Line 28 creates a Stopwatch object called timer. When timer.elapsedTime() is called, this will display the amount of seconds that has been elapsed since timer was constructed. Line 29 calls the selectSort() static method. This method is defined on lines 69-82 and performs a selection sort in descending order. Line 31 shows the time to perform the selection sort, and line 32 checks to see if the array has been sorted correctly by calling the isSorted() static method. The isSorted() method is defined on lines 94-103 and will return true if the passed array is sorted in descending order. Lines 36-40 perform the same thing as lines 28-32, but for the Insertion sort. The insertionSort() static method is defined on lines 83-93. Lines 43-47 does the same thing for the Arrays.sort() method. Note on line 45, that the second argument reverses the order of the array. This is because Arrays.sort() sorts in ascending order, and our check for being sorted assumes descending order. The additional time for reversing the array is not very large so it does not affect our comparisons. Lines 50-54, 56-60 and 62-66 just run the same sorts on the already sorted arrays. The Insertion sort is very efficient on an already sorted array. The following shows some sample runs of this program. java CompareSorts 1000 Selection sort completed: elapsed time: 0.003 array sorted: true Insertion sort completed: elapsed time: 0.002 array sorted: true Arrays.sort() completed: elapsed time: 0.005 array sorted: true Selection sort on sorted array: elapsed time: 0.002 array sorted: true Insertion sort on sorted array: elapsed time: 0.0 array sorted: true Arrays.sort() on sorted array: elapsed time: 0.0 array sorted: true For an array size of 1,000, any of the sorts are fast enough. java CompareSorts 10000 Selection sort completed: elapsed time: 0.144 array sorted: true Insertion sort completed: elapsed time: 0.118 array sorted: true Arrays.sort() completed: elapsed time: 0.01 array sorted: true Selection sort on sorted array: elapsed time: 0.15 array sorted: true Insertion sort on sorted array: elapsed time: 0.001 array sorted: true Arrays.sort() on sorted array: elapsed time: 0.001 array sorted: true For an array size of 10,000, note how the Arrays.sort() method is considerably faster for the unsorted arrays. But, for the sorted arrays, the Insertion sort is also very fast. java CompareSorts 100000 Selection sort completed: elapsed time: 16.704 array sorted: true Insertion sort completed: elapsed time: 15.26 array sorted: true Arrays.sort() completed: elapsed time: 0.053 array sorted: true Selection sort on sorted array: elapsed time: 20.446 array sorted: true Insertion sort on sorted array: elapsed time: 0.002 array sorted: true Arrays.sort() on sorted array: elapsed time: 0.002 array sorted: true For an array size of 100,000, the Arrays.sort() method is much more efficient than the other sorts for unsorted arrays. But, for sorted arrays, the Insertion sort is also very fast.

Order of the sorts

Both the Selection sort and the Insertion sort are order n*n (n-squared) processes. This means that as the array size increases, the time to sort will increase by the square of the size of the array. So, when we increased the size of the array by a factor of 10, the time to sort increases by a factor of 100 (10 squared). The Arrays.sort() method uses a merge sort. This is an order n*log(n) process. This means that time to sort increases at a much slower rate than for the Selection sort or Insertion sort. This is why you see the time differences in the sorting increase dramatically when the array size gets large. The Insertion sort is very efficient for an already sorted array. This is because the number of comparisons is greatly reduced and the number of copies (to move an element to the correct position) is also greatly reduced. Note how the Arrays.sort() method also speeds up for an already sorted array. This is because it will test to see if the array is mostly sorted and substitute an Insertion sort for the merge sort if it finds this to be the case. In other words, the Arrays.sort() method is a clever method.

Is it worth it to claim gambling losses?
Is it worth it to claim gambling losses?

Claiming gambling losses Gambling losses are indeed tax deductible, but only to the extent of your winnings and requires you to report all the...

Read More »
How much would the government take if you won a million dollars?
How much would the government take if you won a million dollars?

That's because when anyone wins the lottery, the IRS withholds 24% of the winnings off the top. With the $2.04 billion Powerball jackpot, if the...

Read More »
How to make $1,000 in a day?
How to make $1,000 in a day?

How to Make 1,000 a Day Get Paid to Do Market Research. One of the fastest ways you can begin making money is by giving your opinion. ... Get Paid...

Read More »
What is the world's number 1 streaming service?
What is the world's number 1 streaming service?

On a global basis, of course, Netflix continues to lead the field with a bit more than 223 million subscribers. Disney has been hot on its heels,...

Read More »