Basic insertion sort optimization is making code slower - java

I'm teaching a demo on Insertion Sort tomorrow. One important optimization is to add a check to the inner loop that stops it from iterating once you get an item into the right position. So basically, it's going from this:
public static void insertionSort(int[] array) {
for (int i = 0; i < array.length; i++) {
for (int j = i; j > 0; j--) {
if (array[j] < array[j-1]) {
int tmp = array[j];
array[j] = array[j-1];
array[j-1] = tmp;
}
}
}
}
to this:
public static void insertionSort(int[] array) {
for (int i = 0; i < array.length; i++) {
for (int j = i; j > 0 && array[j] < array[j-1]; j--) {
int tmp = array[j];
array[j] = array[j-1];
array[j-1] = tmp;
}
}
}
The second version should be more efficient. However, when I benchmark it, I'm actually measuring the performance of the first version as faster. I can't find the bug. Any ideas what's going on?
Here's the code I'm using to benchmark:
import java.util.Arrays;
import java.util.Random;
public class InsertionSort {
public static void main(String[] args) {
int[] stuff = getRandomArray(50000);
//System.out.println(Arrays.toString(stuff));
long started = System.currentTimeMillis();
insertionSort(stuff);
long finished = System.currentTimeMillis();
long totalTime = finished - started;
//System.out.println(Arrays.toString(stuff));
System.out.println("Started: " + started);
System.out.println("Finished: " + finished);
System.out.println("Elapsed: " + totalTime);
}
public static int[] getRandomArray(int size) {
int[] array = new int[size];
Random r = new Random();
for (int i = 0; i < array.length; i++) {
array[i] = r.nextInt(size);
}
return array;
}
public static void insertionSort(int[] array) {
// Implementation goes here
}
}
Edit: Changed the number of items in the test array, and commented out the lines to print

First of all you have written a so called microbenchmark. Your results are not meaningful because you don't have a warmup phase. This is essential to let the JVM HotSpot compiler perform its runtime optimizations.
Search for "java microbenchmark" to find some tools. An example is http://java-performance.info/jmh/
Just in case your results are meaningful I suppose that in your 2nd example the loop optimization of the HotSpot compiler is not as efficient as it is in your 1st example.

Related

Issue trying to create a Bubble Sort using ArrayList<Integer>

Hi I'm trying to figure out how to use BubbleSort in Java and my code is erroring and I don't know why
import java.util.ArrayList;
public class SortsRunner {
public static void BubbleSort(ArrayList<Integer> nums) {
ArrayList<Integer> arr = new ArrayList<Integer>();
int n = arr.size();
for (int i = 0; i < n-1; i++)
for (int j = 0; j < n-i-1; j++)
if (arr.get(j) > arr.get(j+1))
{
int temp = arr.get(j);
arr.get(j) = arr.get(j+1);
arr.get(j+1) = temp;
}
}
public static void SelectionSort(ArrayList<Integer> nums) {
}
public static void printArrayList(ArrayList<Integer> nums) {
for(int i = 0; i < nums.size(); i++) {
System.out.println(nums.get(i) + " ");
}
System.out.println();
}
public static ArrayList<Integer> makeRandomArrayList() {
ArrayList<Integer> nums = new ArrayList<>();
for(int i = 0; i < (int)(Math.random() * 11) + 5; i++) {
nums.add((int)(Math.random() * 100));
}
return nums;
}
public static void main(String[] args) {
printArrayList(makeRandomArrayList());
}
}
When I get to arr.get(j) = arr.get(j+1); and arr.get(j+1) = temp; the left side errors saying "The left-hand side of an assignment must be a variable." can anyone help me fix this?
arr.get(j) = arr.get(j+1);
arr.get(j+1) = temp;
You're trying to assign a value to the result of a method call.
You just can't do this. You can only assign to a local variable, a field in the current class, a field access (e.g. foo.bar = ...) or an array element (e.g. foo[0] = ...).
Instead, you should use set to update a list element:
arr.set(j, arr.get(j+1));
arr.set(j+1, temp);
For the specific case of swapping two elements around in a list, you can instead use Collections.swap:
Collections.swap(arr, j, j+1);
You are doing several things wrong.
The obivous get and set issues already mentioned.
The fact that your are sorting an empty list. You pass in nums but sort the one you create which is empty.
You should use a boolean to prevent unnecessary repeats of the outer loop. Think of it like this, if you don't make a swap on the first iteration of the outer loop, then you won't swap on subsequent iterations.
And one style suggestion. Don't use loops or if statements without {}. Even if they only contain a single line of code. You will be less likely to make coding errors if you do so.
Try the following:
public static void BubbleSort(List<Integer> nums) {
int n = nums.size();
for (int i = 0; i < n; i++) {
boolean swapped = false;
for (int j = 0; j < n-1; j++) {
if (nums.get(j) > nums.get(j + 1)) {
int temp = nums.get(j);
nums.set(j, nums.get(j + 1));
nums.set(j + 1, temp);
swapped = true;
}
}
if (!swapped) {
break;
}
}
}

Changing sorting algorithm java

starting Java coder here. I was wondering how to change my code so it would sort array by always swapping the biggest value to first. Sample output should be:
[3, 1, 2, 0] [3, 2, 1, 0].
public class Sorting {
static void biggest(int[] arr, int start, int end) {
for (start = 0; start < arr.length; start++) {
for (end = start + 1; end < arr.length; end++) {
if (arr[start] < arr[end]) {
int temp = arr[end];
arr[end] = arr[start];
arr[start] = temp;
System.out.println(Arrays.toString(arr));
}
}
}
}
public static void main(String[] args) {
int[] arr = {0, 1, 2, 3};
int temp = 0;
for (int i = 0; i < 4; ++i) {
biggest(arr, temp, 4 - 1);
for (int j = 0; j < 4; ++j) {
}
++temp;
}
}
Thanks in advance,
- Em
If you just want the sort to be successful, I suggest taking advantage of Java's built in sort method then reversing the list as suggested here:
Arrays.sort(arr);
ArrayUtils.reverse(arr);
But it sounds like the spirit of your question is to modify your code for this purpose. Here's the solution I came up with:
import java.util.Arrays;
public class Sorting {
static void biggest(int[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.println(Arrays.toString(arr));
int max, maxAt = i;
for (int j = i; j < arr.length; j++) {
maxAt = arr[j] > arr[maxAt] ? j : maxAt;
}
max = arr[maxAt];
if (arr[i] < max) {
arr[maxAt] = arr[i];
arr[i] = max;
}
}
}
public static void main(String[] args) {
int[] arr = {0, 1, 2, 3};
biggest(arr);
System.out.println(Arrays.toString(arr));
}
}
First off, you had a lot of extra code that you didn't need. It's a bad idea to have a loop in your main. That should be handled by the helper function. You also had a lot of redundant declarations (like start and end). You were on the right track with your helper function, but because of your main loop your time complexity was 0(n²). Eliminating that allows mine to be O(logn). Complexity aside, the key difference in terms of logic is here in your internal loop:
for (end = start + 1; end < arr.length; end++) {
if (arr[start] < arr[end]) {
int temp = arr[end];
arr[end] = arr[start];
arr[start] = temp;
In this loop you're switching the array entry with the first one you find that's bigger. This will result in unwanted early switches (like 1 & 2). Here is my solution:
for (int j = i; j < arr.length; j++) {
maxAt = arr[j] > arr[maxAt] ? j : maxAt;
}
max = arr[maxAt];
if (arr[i] < max) {
arr[maxAt] = arr[i];
arr[i] = max;
}
The key difference is that I search for the maximum value entry following the one we're swapping. That way as we proceed through the array we will always bring forward the next biggest.
Best of luck learning Java I hope this helps!

What algorithm is this?

I cannot seem to make sense of this particular algorithm. It seems to be a bubblesort but not in a traditional sense. What is it?
public static void main(String[] args)
{
double[] a = {0.75, 0.5, 1.0};
sort(a);
for (int i = 0; i < a.length; i++)
System.out.println(a[i]);
}
public static void sort(double[] tal)
{
double p = 0;
int k = 0;
for (int i = 0; i < tal.length - 1; i++)
{
k = i;
for (int j = i + 1; j < tal.length; j++)
{
if (tal[j] < tal[k])
k = j;
}
p = tal[i];
tal[i] = tal[k];
tal[k] = p;
}
}
At first, I incorrectly thought it an Insertion sort. It is a Selection sort (from the Wikipedia entry)
It is a selection sort. The inner loop finds the smallest among the remaining elements which is then exchanged with the first element of the unsorted range.
It's selection sort. Insertion sort works with a forand a while loop.

Java: Combination of recursive loops which has different FOR loop inside; Output: FOR loops indexes

currently recursion is fresh & difficult topic for me, however I need to use it in one of my algorithms.
Here is the challenge:
I need a method where I specify number of recursions (number of nested FOR loops) and number of iterations for each FOR loop. The result should show me, something simmilar to counter, however each column of counter is limited to specific number.
ArrayList<Integer> specs= new ArrayList<Integer>();
specs.add(5); //for(int i=0 to 5; i++)
specs.add(7);
specs.add(9);
specs.add(2);
specs.add(8);
specs.add(9);
public void recursion(ArrayList<Integer> specs){
//number of nested loops will be equal to: specs.size();
//each item in specs, specifies the For loop max count e.g:
//First outside loop will be: for(int i=0; i< specs.get(0); i++)
//Second loop inside will be: for(int i=0; i< specs.get(1); i++)
//...
}
The the results will be similar to outputs of this manual, nested loop:
int[] i;
i = new int[7];
for( i[6]=0; i[6]<5; i[6]++){
for( i[5]=0; i[5]<7; i[5]++){
for(i[4] =0; i[4]<9; i[4]++){
for(i[3] =0; i[3]<2; i[3]++){
for(i[2] =0; i[2]<8; i[2]++){
for(i[1] =0; i[1]<9; i[1]++){
//...
System.out.println(i[1]+" "+i[2]+" "+i[3]+" "+i[4]+" "+i[5]+" "+i[6]);
}
}
}
}
}
}
I already, killed 3 days on this, and still no results, was searching it in internet, however the examples are too different. Therefore, posting the programming question in internet first time in my life. Thank you in advance, you are free to change the code efficiency, I just need the same results.
// ...
recursion (specs, specs.size () - 1);
// ...
public void recursion(ArrayList<Integer> specs, int startWith){
for (int i = 0; i < specs.get(startWith); i++) {
// ...
if (startWith - 1 >= 0)
recursion (specs, startWith - 1);
}
}
Your function also need to now the index of the specs array to use for iteration, and also the previous numbers that should be printed:
public void recursion(ArrayList<Integer> specs, int index, String output) {
if( index >= specs.size() ) {
System.out.println(output);
return;
}
for (int i = 0; i < specs.get(index); i++ )
recursion( specs, index+1, Integer.toString(i) + " " + output );
}
The you should call it like this:
ArrayList<Integer> specs= new ArrayList<Integer>();
specs.add(5);
specs.add(7);
specs.add(9);
specs.add(2);
specs.add(8);
specs.add(9);
recursion( specs, 0, "" );
Does this snippet give the output you want? (It is compileable and executeable)
import java.util.ArrayList;
import java.util.List;
public class SO {
static ArrayList<Integer> specs = new ArrayList<Integer>();
static int[] i;
public static void main(String[] args) throws Exception {
specs.add(5); //for(int i=0 to 5; i++)
specs.add(7);
specs.add(9);
specs.add(2);
specs.add(8);
specs.add(9);
i = new int[specs.size()];
printMe(0, specs, i);
}
static void printMe(int depth, List<Integer> _specs, int[] i) {
if (_specs.isEmpty()) {
System.out.println(printI(i));
return;
} else {
for (int j = 0; j < _specs.get(0); j++) {
i[depth] = j + 1; // + 1 since you seems to want to go from 1 and not 0
printMe(depth + 1, _specs.subList(1, _specs.size()), i);
}
}
}
static String printI(int[] i) {
StringBuilder sb = new StringBuilder();
for (int j = 0; j < i.length; j++) {
sb.append(i[j]);
if (j < i.length - 1) {
sb.append(" ");
}
}
return sb.toString();
}
}
You can try this :
public static void loops(ArrayList<Integer> specs, int idx, StringBuilder res){
if(idx==specs.size()-1){
for (int i = 0; i < specs.get(idx); i++) {
System.out.println(i+" "+res);
}
}
else{
for(int i=0;i<specs.get(idx);i++){
res.insert(0,i+" ");
loops(specs,idx+1,res);
res.delete(0, 2);
}
}
}
And call with :
ArrayList<Integer> specs= new ArrayList<Integer>();
specs.add(5); //for(int i=0 to 5; i++)
specs.add(7);
specs.add(9);
specs.add(2);
specs.add(8);
specs.add(9);
loops(specs,0, new StringBuilder());

Implementation of selection sort in Java

I think I have done the selection sort but I am not sure. Is this really an implementation of selection sort?
static void selectionSort()
{
int min = Integer.MIN_VALUE;
int n = 0;
for(int I=0; I<arraySize; I++)
{
min = dataArray[I];
for(int j=I; j<n; j++)
{
if(dataArray[min]<dataArray[j])
{
min = j;
if(dataArray[min] < dataArray[I])
{
int temp = dataArray[I];
dataArray[I] = dataArray[min];
dataArray[min] = temp;
}
}
}
}
}
I'm not sure I understand how your algorithm works at all. Specifically, you do
min = dataArray[i];
and then later
dataArray[min]<dataArray[j]
i.e. you treat min both as a value in the array, and an index.
Selection sort works as follows:
Find the minimum value in the list
Swap it with the value in the first position
Repeat the steps above for the remainder of the list
(source)
The changes required for your code to accurately implement selection sort would be the following:
Change the inner loop to just find the index of the smallest element. Call it minIndex for instance.
Do the swapping after the inner loop. i.e., swap element at index I with minIndex.
Oh, and as DonCallisto points out in the comments, you may want to do n = dataArray.length instead of n = 0 :-)
public class SelectionSort {
/**
* #Author Chandrasekhara Kota
*/
public static void main(String[] args) {
int arr[]={9,1,8,5,7,-1,6,0,2,2718};
int sortedArr[]=selectionSort(arr);
for (int i = 0; i <sortedArr.length; i++)
{
System.out.println(sortedArr[i]);
}
}
private static int[] selectionSort(int[] arr) {
int minIndex, tmp;
int n = arr.length;
for (int i = 0; i < n - 1; i++)
{
minIndex = i;
for (int j = i + 1; j < n; j++)
if (arr[j] < arr[minIndex])
minIndex = j;
if (minIndex != i) {
tmp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = tmp;
}
}
return arr;
}
}
Here is a selection sort implementation in java -
public class SelectionSort {
static int intArray[] = { 10, 5, 100, 1, 10000 };
public static void doSort() {
for (int outer = 0; outer < intArray.length; outer++) {
int minPosition=outer;
for(int inner=outer;inner<intArray.length;inner++){
if(intArray[inner]<intArray[minPosition]){
minPosition=inner;
}
}
int temp=intArray[minPosition];
intArray[minPosition]=intArray[outer];
intArray[outer]=temp;
}
}
public static void printArray() {
for (int i = 0; i < intArray.length; i++) {
System.out.print(" " + intArray[i]);
}
}
public static void main(String args[]) {
System.out.print("Array Before Sorting->");
printArray();
doSort();
System.out.print("\nArray After Sorting ->");
printArray();
}
}
The above code is picked from - http://www.javabrahman.com/algorithms-in-java/selection-sort-in-java/. This link has detailed explanation on the working of the above code just in case you need the same.

Categories

Resources