Using Insertion Sort to sort an array - java

I'm supposed to take an array of the numbers: {51, 63, 48, 98, 75, 63, 92, 30, 32, 32, 36, 89, 4, 76, 73, 90, 64, 99, 36, 96} and sort them from lowest to highest, and then highest to lowest.
When I try to print the highest to lowest it makes the first output the same. Does anyone see any errors in my code?
package l7c14sort;
import java.util.Arrays;
public class L7C14Sort {
public static void main(String a[]){
int[] arr1 = {51, 63, 48, 98, 75, 63, 92, 30, 32, 32, 36, 89, 4, 76, 73, 90, 64, 99, 36, 96};
int[] arr2 = doInsertionSort(arr1);
int[] arr3 = doInsertionSortAgain(arr1);
System.out.println("Original input: "+Arrays.toString(arr1)+"\n");
System.out.println("Lowest to highest:\n");
for(int i:arr2)
{
System.out.print(i);
System.out.print(", ");
}
System.out.println("\n\n");
System.out.println("Highest to lowest:\n");
for(int k:arr3)
{
System.out.print(k);
System.out.print(", ");
}
System.out.println("\n");
}
public static int[] doInsertionSort(int[] input){
int temp;
for (int i = 1; i < input.length; i++) {
for(int j = i ; j > 0 ; j--){
if(input[j] < input[j-1]){
temp = input[j];
input[j] = input[j-1];
input[j-1] = temp;
}
}
}
return input;
}
public static int[] doInsertionSortAgain(int[] input2){
int temp2;
for (int k = 1; k < input2.length; k++) {
for(int j = k ; j > 0 ; j--){
if(input2[j] > input2[j-1]){
temp2 = input2[j];
input2[j] = input2[j-1];
input2[j-1] = temp2;
}
}
}
return input2;
}
}
Output:
Original input: [99, 98, 96, 92, 90, 89, 76, 75, 73, 64, 63, 63, 51,
48, 36, 36, 32, 32, 30, 4]
Highest to lowest:
99, 98, 96, 92, 90, 89, 76, 75, 73, 64, 63, 63, 51, 48, 36, 36, 32, 32, 30, 4,
Lowest to highest:
4,30,32,32,36,36,48,51,63,63,64,73,75,76,89,90,92,96,98,99

Good news: Your algorithm works fine.
In Java, arrays are passed by reference, not by value. What this means is that when you set int[] arr2 = doInsertionSort(arr1);, the array arr2 is being set to the result of your doInsertionSort method, which returns its input parameter after sorting it. Basically, arr1, arr2, arr3, input and input2 are all pointing to the very same array.
You have two easy options to fix the fact that you're printing:
Restructure main() so that you use one array: print its contents, sort it lowest to highest, print its contents again, sort it highest to lowest, then print its contents again. (This is probably what your instructor intends for you to do, if this is coursework.)
Make a copy of the input parameter to operate on. You can do this with System.arraycopy() like so:
int[] myArray;
System.arraycopy(input, 0, myArray, 0, input.length );
Then, for option 2, you would need to edit your method to use myArray instead of input for every other time you use input.
As a note, you don't need to call your variables input2, temp2, etc. Just like i, j and k go out of scope and are forgotten after the end of a for loop, your variables input and temp mean nothing outside of the block you declared them in.
Hope this helps!

You are ended up with same results, because arrays are mutable. Because of the following code, input array is mutated and its final value is printed.(Highest to lowest).
int[] arr2 = doInsertionSort(arr1);
int[] arr3 = doInsertionSortAgain(arr1);
If you organize your code like:
public static void main(String a[]) {
int[] arr1 = {51, 63, 48, 98, 75, 63, 92, 30, 32, 32, 36, 89, 4, 76, 73, 90, 64, 99, 36, 96};
System.out.println("Original input: " + Arrays.toString(arr1) + "\n");
System.out.println("Lowest to highest:\n");
int[] arr2 = doInsertionSort(arr1);
for (int i : arr2) {
System.out.print(i);
System.out.print(", ");
}
System.out.println("\n\n");
System.out.println("Highest to lowest:\n");
int[] arr3 = doInsertionSortAgain(arr1);
for (int k : arr3) {
System.out.print(k);
System.out.print(", ");
}
System.out.println("\n");
}
You are going to get:
Original input: [51, 63, 48, 98, 75, 63, 92, 30, 32, 32, 36, 89, 4, 76, 73, 90, 64, 99, 36, 96]
Lowest to highest:
4, 30, 32, 32, 36, 36, 48, 51, 63, 63, 64, 73, 75, 76, 89, 90, 92, 96, 98, 99,
Highest to lowest:
99, 98, 96, 92, 90, 89, 76, 75, 73, 64, 63, 63, 51, 48, 36, 36, 32, 32, 30, 4,

Related

Write a program to display even numbers from 1 to 100 seperated by comma

Write a program to display even numbers from 1 to 100 seperated by
comma
public class Evennumbers {
public static void main(String[] args) {
int i=1;
while(i<=100)
{
if(i%2==0)
System.out.print( i+" ,");
i++;
}
}
}
The Out put of the program is placed below :
2 ,4 ,6 ,8 ,10 ,12 ,14 ,16 ,18 ,20 ,22 ,24 ,26 ,28 ,30 ,32 ,34 ,36 ,38
,40 ,42 ,44 ,46 ,48 ,50 ,52 ,54 ,56 ,58 ,60 ,62 ,64 ,66 ,68 ,70 ,72
,74 ,76 ,78 ,80 ,82 ,84 ,86 ,88 ,90 ,92 ,94 ,96 ,98 ,100 ,
/** I want to remove comma after 100 **/
Try it like this. Print the first number and then print the rest preceded by a comma.
String comma = "";
for(int i = 2; i <= 100; i+= 2) {
System.out.print(comma + i);
comma = ", ";
}
prints
2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42,
44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 82,
84, 86, 88, 90, 92, 94, 96, 98, 100

looking for a sorting algorithm that can sort 1-100 using the least amount of statements

As the title says, I am looking for a sorting algorithm that can sort the numbers between 1 and 100 using the least amount of statements in only one method which is the main.
Here's an example to give you an idea on how I can check it(using a counter)
class Solution{
public static void main(String[] args) {
//declaration
int count = 0,inner, outer, temp, h = 1; count++;
int [] array = {100, 99, 98, 97, 96, 95, 94, 93, 92, 91, 90, 89, 88, 87, 86, 85, 84, 83, 82, 81, 80, 79, 78, 77, 76, 75, 74, 73, 72, 71, 70, 69, 68, 67, 66, 65, 64, 63, 62, 61, 60, 59, 58, 57, 56, 55, 54, 53, 52, 51, 50, 49, 48, 47, 46, 45, 44, 43, 42, 41, 40, 39, 38, 37, 36, 35, 34, 33, 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1,}; count++;
System.out.println("Before: " + Arrays.toString(array)); count++;
//start of the sort
while (h <= array.length / 3) //start of while loop 1
{
h = h * 3 + 1; count++;
}count++; //end of while loop 1
while (h > 0) //start of while loop 2
{
for (outer = h; outer < array.length; outer++) //start of for loop
{
temp = array[outer]; count++;
inner = outer;count++;
while (inner > h - 1 && array[inner - h] >= temp) //start of while loop 3
{
array[inner] = array[inner - h]; count++;
inner -= h; count++;
}count++; //end of for loop 3
array[inner] = temp; count++;
}count++; //end of for loop
//equation to count for
count = count + array.length-h+1 + array.length - h +1 -1;
h = (h - 1) / 3; count++;
}count++; //end of while loop 2
System.out.println("After: " + Arrays.toString(array) + "\n" + "Counter = " + count);
}
}
The fastest algorithm with example would be quicksort, also as you are asking i believe this would also take the least amount of statments. Below you can find a link and also description of how it works.
https://www.geeksforgeeks.org/quick-sort/

Java: Selection Sort My implementation vs. another

The following is my implementation of Selection Sort:
package algorithm.selectionsort;
public class SelectionSort {
public static void main(String[] args) {
int[] myArray = selectionSort(new int[] { 9, 9, 9, 8, 7, 73, 32, 109, 1100, 432, 321, 0 });
for (int element : myArray) {
System.out.print("" + element + " ");
}
}
public static int[] selectionSort(int[] a) {
int min;
for (int i = 0; i < a.length - 1; i++) {
min = i;
for (int j = i + 1; j < a.length; j++) {
if (a[j] < a[min]) {
min = j;
int temp = a[i];
a[i] = a[min];
a[min] = temp;
}
}
}
return a;
}
}
I noticed that my instructor codes it slightly differently:
public static int[] selectionSort(int[] a) {
int min;
for (int i = 0; i < a.length - 1; i++) {
min = i;
for (int j = i + 1; j < a.length; j++) {
if (a[j] < a[min]) {
min = j;
}
}
int temp = a[i];
a[i] = a[min];
a[min] = temp;
}
return a;
}
Both implementations work. I'm curious as to what the difference here is. Is it efficiency?
The difference between your instructor's and yours is that he iterate through the array and for each element, search for the minimum, then perform a swap with the element after the wall index.
For yours, you iterate through the array and for each element, while searching for the minimum, if current value is < then the current tentative min, perform a swap with the element after the wall index.
So instead of swapping n times, you could possible swap n*n times for worst case:
Your swap for just one pass (worst case):
100, 90, 88, 70, 55, 43, 32, 28, 19, 10
90, 100, 88, 70, 55, 43, 32, 28, 19, 10
88, 100, 90, 70, 55, 43, 32, 28, 19, 10
70, 100, 90, 88, 55, 43, 32, 28, 19, 10
55, 100, 90, 88, 70, 43, 32, 28, 19, 10
43, 100, 90, 88, 70, 55, 32, 28, 19, 10
32, 100, 90, 88, 70, 55, 43, 28, 19, 10
28, 100, 90, 88, 70, 55, 43, 32, 19, 10
19, 100, 90, 88, 70, 55, 43, 32, 28, 10
10, 100, 90, 88, 70, 55, 43, 32, 28, 19
Your instructor's swap for just one pass (worst case):
100, 90, 88, 70, 55, 43, 32, 28, 19, 10
10, 90, 88, 70, 55, 43, 32, 28, 19, 100
In essence, you swap the values while in the midst of searching for the min. The "min" you swapped may not be the lowest value in the array.
ofcouse your instructor's code is more efficiency and more elegant.
What is Selection Sort?
The algorithm divides the input list into two parts: the sublist of items already sorted, which is built up from left to right at the front (left) of the list, and the sublist of items remaining to be sorted that occupy the rest of the list. Initially, the sorted sublist is empty and the unsorted sublist is the entire input list. The algorithm proceeds by finding the smallest (or largest, depending on sorting order) element in the unsorted sublist, exchanging (swapping) it with the leftmost unsorted element (putting it in sorted order), and moving the sublist boundaries one element to the right.
If the length of the list to be sorted is n, then just n times of exchange should be done, but in your code, it's n*(n-1)*(n-2)....

When running my program, nothing is shown in the console

public class quartz {
public static void main (String[] args) {
int i = 0;
int sum = 0;
int[] n1 = {54, 40, 37, 64, 81, 15, 65, 72, 61, 57, 83, 3, 67, 12, 30, 54, 11, 51, 3, 78, 48, 31, 68, 77, 64, 68, 95, 68, 35, 82, 57, 26, 67, 41, 47, 80, 36, 88, 5, 9, 55, 87, 77, 8, 65, 31, 7, 79, 49, 22, 32, 94, 34, 12, 20, 30, 91, 12, 57, 77, 37, 96, 22, 29, 17, 76, 36, 56, 80, 33, 20, 65, 57, 40, 50, 97, 20, 92, 25, 14, 19, 84, 12, 62, 20, 42, 99, 52, 88, 29, 75, 48, 27, 73, 46, 72, 48, 84, 19, 55};
while (i < n1.length)
sum += n1[i];
i = 0;
System.out.println("Sum: " + sum + ".");
System.out.println("Average: " + (sum/n1.length) + ".");
double[] NE = {-0.6179074665219488, 0.012080423982449795, -0.21346000509541063, 0.08299652983289585, 2.44401680106775, 4.902778859313734, 1.7132831483350532, -4.2004763396051725, -4.043856195861675, -2.6728507023602326, 5.181911533071974, -2.1235877432845354, 7.603895698367564, -5.6730748575837975, -3.5868701412258464, 8.50824673494424, 1.9530312960520657, 1.4057711751329447, -6.6010520166956885, -0.8889270825881894, -3.066437913144831, -1.047977711607209, -0.6183425325427638, -1.9567474971238643, -1.6108985491087715, -3.4762343504063105, -0.7819967483948718, 1.2787199500848474, -1.724036624119682, 4.134045084705252, -4.302090407212001, 4.522452909896921, -9.510982189042458, 4.483571903648103, 4.734972592935479, 1.3007048393668028, -1.5733757395516363, -1.9343054344201707, 6.787212280236046, -0.35603892339489995, -1.3414921239899753, -0.9393551256779856, -1.9298884254368263, 6.043295105337908, 2.9330671137121733, 2.8561036619044047, -0.8293767467550212, 6.123622142714353, -2.2350961485598777, 7.20722805161423, 5.515389689089437, -2.7666432567169745, -4.344590134196103, 3.3453531590362613, 10.413288779778698, 0.3986583788822756, 1.8156402784897105, -6.495232639280744, -2.5586148068696852, 2.456750085945401, -2.0241915465317994, 2.6640207424833706, -3.221638093253812, -0.13291701098446618, 4.525894152095317, 3.833943185257407, -2.892260297173234, -3.247865929061468, 6.129696012756685, 4.451839001858698, -3.142375819178058, -1.0758596832313212, -7.85705595464708, -3.376343621066232, -3.993944532318441, 13.146850947670861, -1.3900676627648902, 3.8600378751921256, 3.9652071948870447, -2.4382860496298324, 3.0864605092488304, -10.769089293963074, 1.9773754511588617, 4.826841112732377, 7.9219782116860324, -3.266132871461332, 1.8118819669439024, 0.698579723806034, 7.119629551067371, -0.9141128559070014, 1.5143207368301361, -8.587596597534729, -0.9387144566983379, 2.5641381148921805, 10.628593146418485, 3.794317923770138, 6.2802756227726615, -0.05171930511667566, 0.8736426098894451, 0.6226851580000003};
double[] NW = {9.631212195521316, -2.1235831279282698, 3.7468670477204773, -4.559878135521824, 3.2444286767576545, 6.2877828741148605, 6.520597627024687, 2.642307472836288, 1.2002893113069557, 0.32620641006622675, -3.368962812990781, -2.588868228199504, 4.356518441561512, -0.5955112302723241, 0.3875648501871751, -2.9311051175998064, 2.0095554763173666, -1.228769483871199, 5.900445902470515, 0.41527619439744434, 2.9752128071432145, 4.805920315662717, -4.797853823364673, 5.752192282393844, 2.9073605365834556, 2.4870719041084497, -1.7994046436584152, 7.79554996548367, 4.4174973514255536, 2.084039895979635, 0.6281302992116424, -3.1466915662704524, 3.646400672147826, 0.9609952887592054, -6.070082172976056, -0.9392599054917704, 0.904301836858967, 5.926867039519574, 3.238559698585232, -4.439332575192746, 1.352444182896236, -0.24594080100384297, -1.6395807550351367, 3.591208179788307, 4.15757174804611, -3.5334824535956173, 0.5302366137985215, 9.564674975899017, 4.175389023096817, -0.9827335882191762, 4.305890552392608, 3.059083687714633, 2.3224548745551488, 0.1934380213592375, 1.0235814, 1.1716370685853148, -2.931711339626567, -4.214035402157694, -1.0093422753964358, -4.843082160061708, -7.148710177896536, -1.910725804980465, -0.22905523068711164, 3.8200222938181367, -1.744095856344644, 1.354958988184811, 0.9933832752568843, 0.8820951391051288, -2.062035935350486, -7.633897329029599, 0.49911238393151325, -1.1684033502541722, 4.090099097765502, 4.566828839384462, 0.6901115935421007, -4.30695891725898, -5.637531096381548, 2.6920329212478507, -1.522395621132775, 6.351734133984433, 0.4895678835360122, -4.755548841958967, -2.826990702897114, 1.974618789378563, -6.999938959339396, 0.6289774718852977, 3.2732671487606266, -1.2781272997669557, 6.725303989648547, -7.163688015215646, 5.547683884070125, -3.0189942298996213, -0.2487963910538069, -0.46314538549764894, 5.3913279138183645, -4.018219623545416, 6.491084381355617, -1.5629014732514819, -6.557894883162792, -3.856421007612216};
int sumEeven = 0, sumEodd = 0, sumWeven = 0, sumWodd = 0;
while (i < 99) {
sumEeven += NE[i];
sumEodd += NE[i+1];
i += 2;
}
i = 0;
while (i < 99) {
sumWeven += NW[i];
sumWodd += NW[i+1];
i += 2;
}
System.out.println("Front coordinates:");
System.out.println("Latitude: " + sumEeven + " Longitude: " + sumEodd);
System.out.println();
System.out.println("Back coordinates:");
System.out.println("Latitude: " + sumWeven + " Longitude: " + sumWodd);
}
}
This code has no errors, and runs, but the console is empty. I have my run configurations set up correctly, so not sure what the issue is. I also made sure that my console was linked to this project and not another, and it is.
I'm running Eclipse Neon if that changes anything.
Some info about the project, although seemingly irrelevant:
n1 calculates the sum of that array of ints and then take the average of the sum
NE and NW calculate the sum of the even parts of each array and the odd parts of each array, and adds each up individually, and they end up being latitudinal and longitudinal coordinates.
I think your program will never leave this loop what are you trying to do here:
while (i < n1.length)
sum += n1[i];
0 < n1.lenth it's always true
try this and see
while (i < n1.length){
sum += n1[i];
i++;
}

Random Tour Generation Issues

I am trying to generate a random tour from the graph. I am using the adjacency-list method.
There is a problem with the vertices. When I add a vertex to a particular list, the vertex gets added to all the lists in the graph. I do not understand why! Here's the code:
public static void main(String[] args) {
defaultData(6);
}
public static void defaultData(int n) {
Integer costs[] = { 26, 95, 38, 74, 80, 73, 73, 92, 22, 97, 13, 81, 41,
17, 4, 2, 47, 54, 21, 68, 78, 4, 77, 3, 66, 55, 99, 42, 62, 39, 8, 36,
53, 74, 26, 8, 42, 66, 30, 58, 69, 14, 49, 39, 85, 98, 72, 3, 18, 99,
96, 66, 64, 36, 17, 44, 70, 0, 8, 14, 62, 41, 84, 59, 94, 27, 5, 27,
96, 10, 15, 52, 43, 20, 2, 86, 45, 43, 32, 17, 49, 92, 9, 15, 6, 49,
72, 7, 51, 21, 2, 26, 63, 82, 98, 48, 21, 96, 16 };
ArrayList<ArrayList<Integer>> costGraph = new ArrayList<>();
ArrayList<ArrayList<Integer>> completeGraph = new ArrayList<>();
Random rand = new Random(System.currentTimeMillis());
int costIndex = 0;
for (int i = 0; i <= n; i++) {
ArrayList<Integer> cost = new ArrayList<>();
ArrayList<Integer> edge = new ArrayList<>();
for (int j = 0; j <= n; j++) {
if (i == j) {
continue;
}
edge.add(j);
cost.add(costs[costIndex]);
costIndex++;
}
completeGraph.add(edge);
costGraph.add(cost);
}
System.out.println(completeGraph);
ArrayList<ArrayList<Integer>> dummyGraph =
(ArrayList<ArrayList<Integer>>)completeGraph.clone();
ArrayList<ArrayList<Integer>> randomTour = new ArrayList<>();
ArrayList<Integer> dummyList = new ArrayList<>();
for (int i = 0; i <= n; i++) {
randomTour.add(dummyList);
}
System.out.println(dummyGraph);
int edgeCount = 0;
Integer row = rand.nextInt(n);
Integer start = row;
while(edgeCount <= n-1){
//dummyList = dummyGraph.get(row);
// To keep the bounds of the random equal
// to the new reduced size of the lists in the graph
Integer col = dummyGraph.get(row).get(rand.nextInt(n-edgeCount));
randomTour.get(row).add(col);
System.out.println(row);
System.out.println(randomTour);
edgeCount++;
for(int k = 0; k < n; k++)
dummyGraph.get(k).remove(row);
row = col;
}
randomTour.get(row).add(start);
System.out.println(randomTour);
}
I would be very grateful for a timely response. Thanks in advance!
You don't want to do this:
for (int i = 0; i <= n; i++) {
randomTour.add(dummyList);
}
It keeps adding the same reference lots of times, so all the ArrayLists in the ArrayList are actually the same object.
Instead you want to do this:
for (int i = 0; i <= n; i++) {
randomTour.add(new ArrayList<Integer>());
}
That way the ArrayList instances in the ArrayList are all different.
I hope this answer was timely enough!

Categories