Problems with insertion sort - java

I have tried to write an insertion sort algorithm, which I thought should have worked but it does not.
int [] array = {108, 10, 45, 67, 108, 23, 29, 108, 48, 67,902, 2, 32, 74, 108, 902};
for(out = 1; out < array.length; out++) {
min = array[out];
in = out - 1;
while(array[in] > min && in > 0) {
array[in + 1] = array[in];
in--;
}
array[in] = min;
}
The output I get when it is run:
32 45 45 45 45 48 67 74 108 108 108 108 902 902 902 902
The expected output is:
2, 10, 23, 29, 32, 45, 48, 67, 67, 74, 108, 108, 108, 108, 902, 902

Try this here
int[] array = {902, 902, 48, 108, 32, 45, 45, 67, 74, 108, 45, 45, 3, 108, 902, 108, 902};
for (int i = 1; i < array.length-1; i++) {
int x = array[i];
int j = i;
while (j > 0 && array[j-1] > x) {
array[j] = array[j-1];
j = j - 1;
}
array[j] = x;
}
System.out.println(Arrays.toString(array));

/**
* Insertion sort O(n^2)
* #author shohanur rahaman
*/
public class insertionSort {
public static void main(String args[]){
int[] ara = {5,32,99,0,6,-12,19};
for(int i=1;i<ara.length;i++){
int tmp = ara[i];
int j=i-1;
while(j>=0 && tmp<ara[j]){
ara[j+1] = ara[j];
j--;
}
ara[j+1] = tmp;
} // end parent loop
for(int i=0;i<ara.length;i++){
System.out.print(ara[i]+ " ");
}
}
}

Related

Adding up all the elements of each column in a 2D array

So I have this dummy 2D array:
int mat[][] = {
{10, 20, 30, 40, 50, 60, 70, 80, 90},
{15, 25, 35, 45},
{27, 29, 37, 48},
{32, 33, 39, 50, 51, 89}};
I want to add up all the values by columns so it would add 10 + 15 + 27 + 32 and return 84 and so on. I have this so far:
public void sum(int[][] array) {
int count = 0;
for (int rows = 0; rows < array.length; rows++) {
for (int columns = 0; columns < array[rows].length; columns++) {
System.out.print(array[rows][columns] + "\t");
count += array[0][0];
}
System.out.println();
System.out.println("total = " + count);
}
}
Can anyone help with this? Also the System.out.print(array[rows][columns] + "\t" ); prints the array out by rows, is there a way to print it out by columns?
One possible Solution would be to first find maximum size of all sub arrays and iterate that many times to find sum of each column avoiding unavailable values.
public static void main(String[] args) {
int mat[][] = {{10, 20, 30, 40, 50, 60, 70, 80, 90},
{15, 25, 35, 45},
{27, 29, 37, 48},
{32, 33, 39, 50, 51, 89},
};
// Find maximum possible length of sub array
int maxLength = 0;
for (int i = 0; i < mat.length; i++) {
if (maxLength < mat[i].length)
maxLength = mat[i].length;
}
for (int i = 0; i < maxLength; i++) {
int sum = 0;
for (int j = 0; j < mat.length; j++) {
// Avoid if no value available for
// ith column from this subarray
if (i < mat[j].length)
sum += mat[j][i];
}
System.out.println("Sum of Column " + i + " = " + sum);
}
}
Use an ArrayList to get the sum of all the columns.
public static void sum(int[][] array) {
ArrayList<Integer> sums = new ArrayList<>();
for (int row = 0; row < array.length; row++) {
for (int column = 0; column < array[row].length; column++) {
if (sums.size() <= column) {
sums.add(column, 0);
}
int curVal = sums.get(column);
sums.remove(column);
sums.add(column, curVal + array[row][column]);
}
}
for (int i = 0; i < sums.size(); i++) {
System.out.println("Sum of column " + i + " = " + sums.get(i));
}
}
Here is one alternative.
The supplied data.
int mat[][] = { { 10, 20, 30, 40, 50, 60, 70, 80, 90 },
{ 15, 25, 35, 45 }, { 27, 29, 37, 48 },
{ 32, 33, 39, 50, 51, 89 }, };
First, find the maximum length of the array in which to store the sum.
int max = Arrays.stream(mat).mapToInt(a -> a.length).max().orElse(0);
Allocate the new array to hold the sums.
int[] sums = new int[max];
Now just use the Arrays.setAll method to sum them, taking careto not exceed the current array's length.
for (int[] arr : mat) {
Arrays.setAll(sums, i-> i < arr.length ? sums[i] + arr[i] : sums[i]);
}
System.out.println(Arrays.toString(sums));
Prints
[84, 107, 141, 183, 101, 149, 70, 80, 90]
You can use Stream.reduce method to summarise the elements of the rows of the matrix by the columns:
int[][] matrix = {
{10, 20, 30, 40, 50, 60, 70, 80, 90},
{15, 25, 35, 45},
{27, 29, 37, 48},
{32, 33, 39, 50, 51, 89}};
int[] arr = Arrays.stream(matrix)
// summarize in pairs
// the rows of the matrix
.reduce((row1, row2) -> IntStream
// iterate over the indices
// from 0 to maximum row length
.range(0, Math.max(row1.length, row2.length))
// summarize in pairs the elements of two rows
.map(i -> (i < row1.length ? row1[i] : 0) +
(i < row2.length ? row2[i] : 0))
// an array of sums
.toArray())
// the resulting array
.get();
System.out.println(Arrays.toString(arr));
// [84, 107, 141, 183, 101, 149, 70, 80, 90]
See also:
• Sum of 2 different 2d arrays
• How to calculate the average value of each column in 2D array?
…and the same with lambda:
int[] array = Arrays.stream(mat)
.reduce((a1, a2) -> IntStream.range(0, Math.max(a1.length, a2.length))
.map(i -> i < a1.length && i < a2.length ? a1[i] + a2[i]
: i < a1.length ? a1[i] : a2[i] ).toArray()).get();
gets the sums of each column in the int[] array:
[84, 107, 141, 183, 101, 149, 70, 80, 90]

distrubuting people to groups evenly based on userinput

ReadFile randomGenerate = new ReadFile();
Input userNum = new Input();
String classnum = userNum.fileToSelect();
int lineNumber = randomGenerate.lineCounter(classnum);
//number of students in classnum.txt
ArrayList<String> people = randomGenerate.readPeople();
//a string of names(first word on each row)
int userPut = userNum.numInput();
int maxNum = lineNumber/userPut;
Right not, I am reading off a txt file - the first word of each row which is the name of a person. I want to distribute this ArrayList of people into even groups, with the number of groups based on userinput.
int[] numbers = RandomNumbersWithoutRepetition(0, lineNumber, lineNumber);
//an array of numbers IN ORDER
int[] randomNumbers = RandomizeArray(numbers);
//shuffles the array
I generated a set of numbers in order, and then shuffled them, which works fine.
But, my method of grouping people has been based off ifelse conditions which don't work so well. So is there an efficient method to put this ArrayList of names into user-desired groups?
I have x number of students.
I have n number of groups.
I'm assuming there's no other criteria for dividing students into groups.
Basically, you divide the number of groups into the number of students. Yes, you have to deal with a remainder. But it's straightforward.
Here are the results of a test. I created 53 students and shuffled them. I then divided the students into 4 groups. I manually formatted the output to fit in the answer. Group 1 has 14 students, while the remaining groups have 13 students.
Students: 42, 27, 5, 26, 32, 30, 44, 10, 17, 29, 40, 52,
47, 38, 49, 18, 46, 24, 34, 12, 13, 53, 35, 20, 1,
2, 41, 23, 43, 28, 8, 11, 50, 37, 9, 7, 48, 3, 33,
25, 31, 15, 22, 21, 14, 45, 36, 16, 51, 19, 4, 6, 39
Group 1: 42, 27, 5, 26, 32, 30, 44, 10, 17, 29, 40, 52, 47, 38
Group 2: 49, 18, 46, 24, 34, 12, 13, 53, 35, 20, 1, 2, 41
Group 3: 23, 43, 28, 8, 11, 50, 37, 9, 7, 48, 3, 33, 25
Group 4: 31, 15, 22, 21, 14, 45, 36, 16, 51, 19, 4, 6, 39
And here's the code. The groupStudents and sortStudents methods are the methods that do the work.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class StudentGroups {
public static void main(String[] args) {
int numberOfGroups = 4;
int numberOfStudents = 53;
StudentGroups sg = new StudentGroups(numberOfStudents);
sg.printStudents();
List<List<Integer>> groups = sg.groupStudents(
numberOfGroups);
sg.printGroups(groups);
}
private List<Integer> students;
public StudentGroups(int numberOfStudents) {
students = new ArrayList<>(numberOfStudents);
for (int i = 0; i < numberOfStudents; i++) {
students.add(i + 1);
}
Collections.shuffle(students);
}
public void printStudents() {
System.out.print("Students: ");
for (int i = 0; i < students.size(); i++) {
System.out.print(students.get(i));
if (i < (students.size() - 1)) {
System.out.print(", ");
}
}
System.out.println();
}
public List<List<Integer>> groupStudents(int groups) {
List<List<Integer>> output = new ArrayList<>();
int size = students.size();
int group = size / groups;
int remainder = size % groups;
sortStudents(output, size, group, remainder);
return output;
}
private void sortStudents(List<List<Integer>> output,
int size, int group, int remainder) {
List<Integer> list = new ArrayList<>();
int count = 0;
for (int i = 0; i < size; i++) {
list.add(students.get(i));
if (count == 0 && remainder > 0) {
if (group > 0) {
list.add(students.get(++i));
}
remainder--;
}
if (++count >= group) {
addList(output, list);
list = new ArrayList<>();
count = 0;
}
}
addList(output, list);
}
private void addList(List<List<Integer>> output,
List<Integer> list) {
if (list.size() > 0) {
output.add(list);
}
}
public void printGroups(List<List<Integer>> groups) {
for (int j = 0; j < groups.size(); j++) {
System.out.print("Group ");
System.out.print(j + 1);
System.out.print(": ");
List<Integer> students = groups.get(j);
for (int i = 0; i < students.size(); i++) {
System.out.print(students.get(i));
if (i < (students.size() - 1)) {
System.out.print(", ");
}
}
System.out.println();
}
}
}

How does this array print this barchart?

public class BarChart // Modified from Fig 7.6
{
public static void main(String[] args)
{
int[] grades = {90, 71, 89, 75, 83, 87, 81, 100, 99, 83,
65, 100, 91, 78, 88, 62, 55, 84, 73, 89}; // 20 elements
int[] frequency = new int[11]; // 11 ranges
System.out.println("Grade distribution:");
for (int i = 0; i < grades.length; i++) {
frequency[grades[i]/10]++; //How does this work? why does it say 10
}
for (int i = 0; i < frequency.length; i++)
{
if (i == 10) {
System.out.printf("%5d: ", 100);
}
else {
System.out.printf("%02d-%02d: ", i * 10, i * 10 + 9);
}
for (int stars = 0; stars < frequency[i]; stars++) { // How does it know where to print the stars?
System.out.print("*");
}
System.out.println();
}
}
}
Output:
I am having trouble understanding how this program works. I put in some questions as comments to get a clearer answer. I attached a pic of the output as well.
I have commented in the code directly:
public class BarChart // Modified from Fig 7.6
{
public static void main(String[] args)
{
/*array that contains the data that will be used to display the distribution*/
int[] grades = {90, 71, 89, 75, 83, 87, 81, 100, 99, 83,
65, 100, 91, 78, 88, 62, 55, 84, 73, 89}; // 20 elements
/*this frequecncy is used to divided your interval [0,100] in 11 slices*/
int[] frequency = new int[11]; // 11 ranges
System.out.println("Grade distribution:");
for (int i = 0; i < grades.length; i++) {
/*division of your i element of grade array by 10,
10 here is used here to make correspond your grades
to your slices defined in the frequency variable,
(type int divided by 10 will give an int as output
(the decimals are truncated -> equivalent as taking the floor of the number)
so you have an int that can be used as an index for your frequency array,
the grades[i]/10 will be incremented by 1 -> this will allow to print the stars after*/
frequency[grades[i]/10]++;
}
for (int i = 0; i < frequency.length; i++) //loop that will do the display
{
if (i == 10) {
System.out.printf("%5d: ", 100);//this will print the last line of your output,
//printf will not print the EOL char so the other printing operations are done on the same line
}
else {
System.out.printf("%02d-%02d: ", i * 10, i * 10 + 9);
//this is will create your DD-DD intervals (00-09:, 10-19)
}
for (int stars = 0; stars < frequency[i]; stars++) {
// the value stored in frequency thanks to this operation: frequency[grades[i]/10]++; will be displayed,
//you loop from 0 until you reach the value of frequency[i] and display a star at each loop
System.out.print("*");
}
System.out.println();//this will print the end of line character
}
}
}

Searching duplicates in 2 dimensional array

I have 2 dimensional array like :
{2 , 6 , 46, 8 , 7 , 25, 64 , 9 , 10},
{6 , 10, 50, 12, 11, 29, 68 , 13, 14},
{46, 50, 90, 52, 51, 69, 108, 53, 54}
How can I find the duplicate elements like '6', '46' and '50'?
My code finds consecutive duplicates:
for (int i = 0; i < a2.length; i++) {
for (int j = 0; j < a2[i].length; j++) {
cursor = a2[i][j];
if(j + 1 < a2[i].length){
if(cursor == a2[i][j + 1]){
System.out.println(cursor + "has duplicate in this array");
}
}
}
}
Iterate through all elements and save it in a temporary set.
When you encounter a duplicate, the list will contain it.
import java.util.HashSet;
import java.util.HashSet;
public class HelloWorld
{
public static void main(String[] args)
{
int[][] arr = {
{2 , 6 , 46, 8 , 7 , 25, 64 , 9 , 10},
{6 , 10, 50, 12, 11, 29, 68 , 13, 14},
{46, 50, 90, 52, 51, 69, 108, 53, 54}
};
HashSet<Integer> elements = new HashSet<>();
HashSet<Integer> duplicates = new HashSet<>();
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
if(elements.contains(arr[i][j])) {
duplicates.add(arr[i][j]);
}
elements.add(arr[i][j]);
}
}
System.out.println(duplicates.toString());
}
}
Output:
[50, 6, 10, 46]
Try this code:-
import java.util.Arrays;
import java.util.List;
public class ArrayTest {
public static void main(String[] args) {
Integer[][] myarray = new Integer[][]{
{ 10, 20, 30, 40 },
{ 50, 77, 60, 70 },
{ 33, 22, 88, 99 },
{ 21, 66, 65, 21 }
};
int i,j;
for(i=0;i<myarray.length;i++)
{
for(j=0;j<myarray.length;j++)
{
int temp= myarray[i][j];
myarray[i][j]=0;
List<Integer> rowvalues = Arrays.asList(Arrays.asList(myarray).get(i));
Boolean b=rowvalues.contains(temp) ;
if(b==true)
{
System.out.println("duplicate at ["+i+"]["+j+"] is: "+temp);
}
myarray[i][j]=temp;
}
}
}
}

How do you sort numbers in ascending order from a for loop?

i have a for loop that multiples 3 and 7 by all numbers between 1 and 100. It only shows the numbers that are less the 100 after the multiplication though. How would you sort it so that its in ascending order?
for(int i = 1; i<=100; i++){
int result1 = 3 * i;
int result2 = 7*i;
if (result1 <=100){
System.out.println(+result1);
}
if (result2 <= 100){
System.out.println(+result2);
}
}
would use another if statement to sort it?
How about:
for(int i = 1; i<=100; i++){
if(i % 3 == 0 || i % 7 == 0)
System.out.println(i);
}
This sounds like it'll do what you need:
[mike#mike ~]$ cat temp/SO.java
package temp;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class SO {
private static final int MAX_VAL = 100;
public static void main(String[] args) {
List<Integer> results = new ArrayList<Integer>();
for (int i = 1; i <= MAX_VAL; i++) {
int result1 = 3 * i;
int result2 = 7 * i;
if (result1 <= MAX_VAL) {
results.add(result1);
}
if (result2 <= MAX_VAL) {
results.add(result2);
}
}
Collections.sort(results);
System.out.println(results);
}
}
[mike#mike ~]$ javac temp/SO.java
[mike#mike ~]$ java temp.SO
[3, 6, 7, 9, 12, 14, 15, 18, 21, 21, 24, 27, 28, 30, 33, 35, 36, 39, 42, 42, 45, 48, 49, 51, 54, 56, 57, 60, 63, 63, 66, 69, 70, 72, 75, 77, 78, 81, 84, 84, 87, 90, 91, 93, 96, 98, 99]

Categories

Resources