How to print steps when sorting in Java? - java

I have one problem. I need to print time and steps of sorting. I did time but I do not how to print steps.
class BubbleSort {
public static void main(String[] args) {
int[] randomNums = new int[20];
for (int i = 0; i < randomNums.length; i++) {
randomNums[i] = (int) (100 * Math.random());
}
System.out.println("Numbers before sorting: ");
for (int i = 0; i < randomNums.length; i++) {
System.out.print(randomNums[i]+" " );
}
System.out.println();
long time = System.nanoTime();
bubbleSort(randomNums);
long elapsed = System.nanoTime() - time;
System.out.println("\nBubble sort time is " + elapsed + " nanoseconds passed, " + elapsed / 1000000000 + " seconds passed");
}
static void bubbleSort(int[] arr) {
int numbers = arr.length;
int temp = 0;
for (int i = 0; i < numbers; i++) {
for (int j = 1; j < (numbers - i); j++) {
if (arr[j - 1] > arr[j]) {
//swap elements
temp = arr[j - 1];
arr[j - 1] = arr[j];
arr[j] = temp;
}
}
}
}
}

For listing down steps we can simply use a sysout to do the thing. The crux here is to know how this sorting algo is actually doing the sorting part. The swapping part is the actual sort code.
int step = 0;
for (int i = 0; i < numbers; i++) {
for (int j = 1; j < (numbers - i); j++) {
if (arr[j - 1] > arr[j]) {
//swap elements
System.out.println("step #" + step + ". swapping " + arr[j - 1] + " and " + arr[j])
temp = arr[j - 1];
arr[j - 1] = arr[j];
arr[j] = temp;
step++;
}
}
}

Related

Calculating average time to complete a function in java

I am running a simple sort 1000 times and trying to get the average time it takes to complete (and then compare to another sort) based on a user defined array length. My problem is that when i try to get the time it is always 0. I haven't coded in a while and am not seeing my error.
import java.util.Scanner;
public class TimingExpBubble2 {
public static long average(long[] arr){
int sum = 0;
for (int i = 0; i < arr.length; i++)
sum += arr[i];
return sum / arr.length;
}
public static void main(String args[]) {
Scanner reader = new Scanner(System.in);
System.out.println("Enter array length: ");
int x = reader.nextInt();
long[] time = new long[1000];
for(int i = 0; i < 1000; i++)
{
int[] arr = new int[x];
for(int j = 0; j < arr.length; j++) {
arr[j] = (int) (Math.random() * 5000);
}
long start = System.currentTimeMillis();
for (int l = 0; l < arr.length - 1; l++) {
for (int j = 1; j < arr.length - i; j++) {
if (arr[j - 1] > arr[j]) {
int temp = arr[j - 1];
arr[j - 1] = arr[j];
arr[j] = temp;
}
}
}
reader.close();
long end = System.currentTimeMillis();
time[i] = (end - start);
}
System.out.println("Average time in Miliseconds: " + average(time));
}
}
'''
You need to use System.nanoTime() instead System.currentTimeMillis()
I figured it out with help from a friend.
i needed to put my time variables and measurements as a double since the amounts where so small and it helped to just using a running variable rather than an array
'''
time = time + (end - start);
}
System.out.println("Average time in Miliseconds: " + (time / 1000));
'''

Out of bounds exception when trying to run cocktail code java [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 3 years ago.
I am trying to make a cocktail sort but I am getting an out of bound exception at the line if (a[i] > a[i + 1]) and I'm not sure why.
Here is the full code. Sorry if this is completely wrong.
import java.util.Arrays;
import java.util.Scanner;
public class Cocktail
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int count = 0;
boolean switched = true;
int[]a = new int[10];
for (int i = 0; i < a.length; i++)
{
int value = input.nextInt();
a[i] = value;
}
System.out.println(a[0]);
while (switched == true)
{
switched = false;
for (int i = 0; i < a.length; i++)
{
if (a[i] > a[i + 1])
{
int temp = a[i];
a[i] = a[i + 1];
a[i + 1] = temp;
count++;
switched = true;
}
}
for (int i = a.length; i >= 0; i++)
{
if (a[i] > a[i + 1])
{
int temp = a[i];
a[i] = a[i + 1];
a[i + 1] = temp;
count++;
switched = true;
}
}
if (switched == false)
{
System.out.println(count);
}
}
}
}
you need to Change
if (a[i] > a[i + 1])to be like this --> if (i < a.length-1 && a[i] > a[i + 1]).
The problem was it is trying to reach the 11th element ;)
If you may, here's an Edited version of your code:
Scanner input = new Scanner(System.in);
int count = 0;
boolean switched = true;
int[]a = new int[10];
System.out.println("enter 10 Integers: ");// # Added to make code clearer
for (int i = 0; i < a.length; i++)
{
int value = input.nextInt();
a[i] = value;
}
System.out.println("thankyou, Sorting now!");//# also this one
while(switched == true)
{
switched = false;
for (int i = 0; i < a.length; i++)
{
if (i < a.length-1 && a[i] > a[i + 1]) // <-- # here was the problem
{
int temp = a[i];
a[i] = a[i + 1];
a[i + 1] = temp;
count++;
switched = true;
}
}
for (int i = a.length; i >= 0; i++)
{
if (i < a.length-1 && a[i] > a[i + 1]) //<-- # Also Here
{
int temp = a[i];
a[i] = a[i + 1];
a[i + 1] = temp;
count++;
switched = true;
}
}
if (switched == false)
{
System.out.println("count is "+ count);
}
}
// # added part to print array for testing
System.out.println("Sorted Array:");
for (int i = 0; i <a.length ; i++) {
System.out.print(a[i]+", ");
}
}//main
}//class
Here's the output:
Copy and paste it, Run and Happy Coding =D

Number of Comparisons in Bubble Sort

I am trying to make a method for comparisons in my bubble sort class. However, I keep getting the same value. Is there any way to fix this? Thanks.
public void comparisons(int[] array)
{
int count = 0;
for (int i = 0; i < array.length - 1; i++)
{
for (int j = 0; j < array.length - i - 1; j++)
{
count++;
if ((array[i] > array[i + 1])) //Swaps the elements
{
int temp = array[i];
array[i] = array[i + 1];
array[i + 1] = temp;
}
}
}
System.out.print("\n\nComparisons:" + count);
}
The inner loop index j is not used, and it has incorrect bounds.
public void comparisons(int[] array)
{
int count = 0;
for (int i = 0; i < array.length - 1; i++)
{
for (int j = i; j < array.length - 1; j++)
{
count++;
if ((array[j] > array[j + 1])) //Swaps the elements
{
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
System.out.print("\n\nComparisons:" + count);
}
The outer loop index i is the same value for all the values of j in the inner loop. Looks like the compare logic should be using the inner loop index j.
If count is supposed to record the number of swaps done during the sort, perhaps it needs to be in the block of code performing the swap. At the moment, count++ will always execute the same number of times.
Try this:
public void comparisons(int[] array)
{
int count = 0;
for (int i = 0; i < array.length - 1; i++)
{
for (int j = 0; j < array.length - i - 1; j++)
{
if ((array[i] > array[i + 1])) //Swaps the elements
{
int temp = array[i];
array[i] = array[i + 1];
array[i + 1] = temp;
count++;
}
}
}
System.out.print("\n\nComparisons:" + count);
}
You better try to increment value of count inside the if-condition. You can place count++ anywhere inside if-condition, based upon requirements.

Levenshtein distance in java outputting the wrong number

For my university assignment in java I have been asked to provide "extra analytics functions" I decided to use Levenshtein distance but I have an issue where the number outputted to the console is one less than the actual answer. So the distance between "cat" and "hat" should be 1 but it's displaying as 0
public class Levenshtein {
public Levenshtein(String first, String second) {
char [] s = first.toCharArray();
char [] t = second .toCharArray();
int Subcost = 0;
int[][] array = new int[first.length()][second.length()];
for (int i = 0; i < array[0].length; i++)
{
array[0][i] = i;
}
for (int j = 0; j < array.length; j++)
{
array [j][0]= j;
}
for (int i = 1; i < second.length(); i++)
{
for (int j = 1; j < first.length(); j++)
{
if (s[j] == t [i])
{
Subcost = 0;
}
else
{
Subcost = 1;
}
array [j][i] = Math.min(array [j-1][i] +1,
Math.min(array [j][i-1] +1,
array [j-1][i-1] + Subcost) );
}
}
UI.output("The Levenshtein distance is -> " + array[first.length()-1][second.length()-1]);
}
}
Apparently you're using the following algorithm:
https://en.wikipedia.org/wiki/Levenshtein_distance#Iterative_with_full_matrix
I think you were not too accurate with indices. I'm not sure where exactly the problem is, but here is a working version:
public int calculateLevenshteinDistance(String first, String second) {
char[] s = first.toCharArray();
char[] t = second.toCharArray();
int substitutionCost = 0;
int m = first.length();
int n = second.length();
int[][] array = new int[m + 1][n + 1];
for (int i = 1; i <= m; i++) {
array[i][0] = i;
}
for (int j = 1; j <= n; j++) {
array[0][j] = j;
}
for (int j = 1; j <= n; j++) {
for (int i = 1; i <= m; i++) {
if (s[i - 1] == t[j - 1]) {
substitutionCost = 0;
} else {
substitutionCost = 1;
}
int deletion = array[i - 1][j] + 1;
int insertion = array[i][j - 1] + 1;
int substitution = array[i - 1][j - 1] + substitutionCost;
int cost = Math.min(
deletion,
Math.min(
insertion,
substitution));
array[i][j] = cost;
}
}
return array[m][n];
}

Stopping an inner loop after one correct iteration

The problem in the code is in the goldbach method. I want to stop iteration of the inner two loops after the inner most loop has found one pair of numbers, but I am not getting how to exit just those two loops. In other words, I only want to find only one pair per i integer created by the outermost for loop, and then move on to the next integer i.
Below is my code:
import java.util.Arrays;
import java.awt.List;
import java.util.ArrayList;
// finding prime numbers using sieve of Eratosthenes and golbach's conjecture
public class Test {
public static void main(String[] args) {
int[] num = new int[1000000];
for (int i = 2; i <= num.length; i++) {
num[i - 1] = i;
}
Test.sieve(num);
Test.goldbach(num);
}
public static void sieve(int[] array) {
for (int i = 2; i < Math.sqrt(array.length); i++) {
if (array[i - 1] == 0) {
continue;
}
for (int j = 2 * i; j <= array.length; j += i) {
array[j - 1] = 0;
}
}
for (int i = 0; i < array.length; i++) {
if (array[i] != 0) {
//System.out.print(array[i] + " ");
}
}
//System.out.println(Arrays.toString(array));
}
public static void goldbach(int[] array) {
for (int i = 2; i <= 1000000; i += 2) { //to go through every even integer
for (int j = 0; j <= i; j++) {
for (int k = 0; k <= i; k++) {
System.out.println("two prime numbers that add to " + i + " are " + array[j] + " and " + array[k]);
break;
}
}
}
}
}
}
You could set the value of j in your second loop. eg.
for (int i = 2; i <= 1000000; i += 2) { //to go through every even integer
for (int j = 0; j <= i; j++) {
for (int k = 0; k <= i; k++) {
System.out.println("two prime numbers that add to " + i + " are " + array[j] + " and " + array[k]);
j = i + 1; // This will end the outer loop as well.
break;
}
}
}
}
use a label to break (or continue) a loop other than the inner one:
found:
for (int j = 0; j <= i; j++) {
for (int k = 0; k <= i; k++) {
System.out.println("two prime numbers that add to " + i + " are " + array[j] + " and " + array[k]);
break found;
}
}
}
or use an additional method and return - more indicated if that new method has an own clear function (and better name)
public static void goldbach(int[] array) {
for (int i = 2; i <= 1000000; i += 2) { //to go through every even integer
primeAdd(i);
}
}
private static void primeAdd(int i) {
for (int j = 0; j <= i; j++) {
for (int k = 0; k <= i; k++) {
System.out.println("two prime numbers that add to " + i + " are " + array[j] + " and " + array[k]);
return;
}
}
}
but, as already commented by bureaquete, there is no need for the inner loop since it is always being terminated.

Categories

Resources