Insertion sort: count swaps and comparisons - java

For some reason I can't get the count for comparisons and swap in the InsertionSort part, it just outputs zero. And when I isolate the code for it, it outputs a number of swaps and comparisons (though I don't know if it's wrong or not, probably wrong considering the number is the same for both) and the array is not sorted at all. I'm really confused as to why this isn't working, any help is greatly appreciated!
Update: The instance of bubble was being passed onto both selection and insertion, now that that's fixed turns out T also have a problem with the selection part. Any suggestions on how to fix them?
Update 2: Fixed the selection part! Still confused about insertion.
import java.util.Scanner;
public class Sorting {
public static void main(String[] args) {
int n, c;
Scanner scan = new Scanner(System.in);
System.out.print("Number of elements: ");
n = scan.nextInt();
int[] bubbleSortArray = new int[n];
int[] selectionSortArray = new int[n];
int[] insertionSortArray = new int[n];
System.out.print("Enter " + n + " elements: ");
for (c = 0; c < n; c++) {
int i = scan.nextInt();
bubbleSortArray[c] = i;
selectionSortArray[c] = i;
insertionSortArray[c] = i;
}
BubbleSort(bubbleSortArray);
SelectionSort(selectionSortArray);
InsertionSort(insertionSortArray);
}
static void BubbleSort(int[] array) {
int n = array.length;
int cm = 0;
int sw = 0;
for (int c = 0; c < (n - 1); c++) {
for (int d = 0; d < n - c - 1; d++) {
cm++;
if (array[d] > array[d + 1]) {
int swap = array[d];
array[d] = array[d + 1];
array[d + 1] = swap;
sw++;
}
}
}
System.out.print("Bubble sort: ");
for (int c = 0; c < n; c++) {
System.out.print(array[c] + " ");
}
System.out.println("- " + cm + " comparisons, " + sw + " swaps");
}
static void SelectionSort(int[] array) {
int n = array.length;
int cm = 0;
int sw = 0;
for (int c = 0; c < n - 1; c++) {
int index = c;
for (int d = c + 1; d < n; d++){
cm++;
if (array[d] < array[index])
index = d;
}
int temp = array[index];
sw++;
array[index] = array[c];
array[c] = temp;
}
System.out.print("Selection sort: ");
for (int c = 0; c < n; c++) {
System.out.print(array[c] + " ");
}
System.out.println("- " + cm + " comparisons, " + sw + " swaps");
}
static void InsertionSort(int[] array) {
int n = array.length;
int cm = 0;
int sw = 0;
for (int c = 1; c < n; c++){
int temp = array[c];
for (int d = c - 1; d > 0 && temp < array[d]; d--) {
array[d+1] = array[d];
array[d+1] = temp;
cm++;
sw++;
}
}
System.out.print("Insertion sort: ");
for (int c = 0; c < n; c++) {
System.out.print(array[c] + " ");
}
System.out.println("- " + cm + " comparisons, " + sw + " swaps");
}
}

After you are done with BubbleSort array is sorted, and you are passing that sorted instance to SelectionSort and InsertionSort.
If you want to get the results for each kind of sorts you can do :
int n, c;
Scanner scan = new Scanner(System.in);
System.out.print("Number of elements: ");
n = scan.nextInt();
int[] bubbleSortArray = new int[n];
int[] selectionSortArray = new int[n];
int[] insertionSortArray = new int[n];
System.out.print("Enter " + n + " elements: ");
for (c = 0; c < n; c++) {
int i = scan.nextInt();
bubbleSortArray[c] = i;
selectionSortArray[c] = i;
insertionSortArray[c] = i;
}
BubbleSort(bubbleSortArray);
SelectionSort(selectionSortArray);
InsertionSort(insertionSortArray);

Related

How to set number range from user input into a 2d array

just wanting to know how do i set an input range for the scanner object, which then transfers the values and inputs them into a 2d array.
I was able to set a range for random number generator but i do not know how to apply the same concept to my scanner object
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Random random = new Random();
int rows = 3;
int columns = 5;
System.out.println("Enter array elements : ");
int arry1[][] = new int[rows][columns];
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < columns-2; j++)
{
arry1[i][j] = sc.nextInt();
}
}
arry1[0][3] = random.nextInt(50-10+1)+10;
arry1[1][3] = random.nextInt(50-10+1)+10;
arry1[2][3] = random.nextInt(50-10+1)+10;
int sum1 = 0;
int sum2 = 0;
int sum3 = 0;
sum1 = arry1[0][0]+arry1[0][1]+arry1[0][2]+arry1[0][3];
sum2 = arry1[1][0]+arry1[1][1]+arry1[1][2]+arry1[1][3];
sum3 = arry1[2][0]+arry1[2][1]+arry1[2][2]+arry1[2][3];
arry1[0][4] = sum1;
arry1[1][4] = sum2;
arry1[2][4] = sum3;
System.out.print("DISPLAYING ARRAY:");
System.out.println();
for (int[] x1 : arry1) {
for (int y1 : x1) {
System.out.print(y1 + " ");
}
System.out.println();
}
}
}
Add checking if the value is within range.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Random random = new Random();
int rows = 3;
int columns = 5;
System.out.println("Enter array elements : ");
int arry1[][] = new int[rows][columns];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns - 2; j++) {
int input;
do {
input = sc.nextInt();
} while (input < 0 || input > 3);
arry1[i][j] = input;
}
}
arry1[0][3] = random.nextInt(50 - 10 + 1) + 10;
arry1[1][3] = random.nextInt(50 - 10 + 1) + 10;
arry1[2][3] = random.nextInt(50 - 10 + 1) + 10;
int sum1 = 0;
int sum2 = 0;
int sum3 = 0;
sum1 = arry1[0][0] + arry1[0][1] + arry1[0][2] + arry1[0][3];
sum2 = arry1[1][0] + arry1[1][1] + arry1[1][2] + arry1[1][3];
sum3 = arry1[2][0] + arry1[2][1] + arry1[2][2] + arry1[2][3];
arry1[0][4] = sum1;
arry1[1][4] = sum2;
arry1[2][4] = sum3;
System.out.print("DISPLAYING ARRAY:");
System.out.println();
for (int[] x1 : arry1) {
for (int y1 : x1) {
System.out.print(y1 + " ");
}
System.out.println();
}
}

How to Output the Index of an Element in array

This was the task:
Design, implement and test programs to do each of the following:
a) Find the sum and number of positive integers in a list of 10 integers.
b) Find the smallest number in a list of 10 integers.
c) Determine and output the biggest and smallest numbers in a list of 10 integers.
The output should be of the form :
“The biggest number 304 was at position 3 in the list”
“The smallest number 4 was at position 8 in the list”
So I tried it and the Problem is that everything works except to give me the position of the biggest and smallest number.
import java.util.Arrays;
public class a5_2 {
#SuppressWarnings("unlikely-arg-type")
public static void main (String [] args) {
int m [] = {-3,23,7,12,4,-44,2,21,3,43} ;
System.out.println("Array: " + Arrays.toString(m));
int[] pos = findNumber(m);
System.out.println("Array without negatives: ");
for (int i = 0; i < pos.length; i++)
{
System.out.println(pos[i]);
}
System.out.println("Number of pos num: " + pos.length);
int sum = 0;
for (int i : pos)
sum += i;
System.out.println("Sum of pos num: " + sum);
int [] small = findSmallest(pos);
System.out.println("Smallest Number: ");
System.out.println(small[0] + " at pos: " + Arrays.asList(pos).indexOf(small[0]));
int [] big = findBiggest(pos);
System.out.println("Biggest Number: ");
System.out.println(big[0] + " at pos: " + Arrays.asList(pos).indexOf(big[0]));
}
public static int [] findNumber(int[] sum) {
int num = 0;
int n [] = new int [sum.length];
for(int i = 0; i < sum.length; i++)
{
if (sum[i] > 0)
{
n[num] = sum[i];
num++;
}
}
int [] pos = new int [num];
for (int k = 0 ; k < num ; k++)
{
pos[k] = n[k];
}
return pos;
}
public static int [] findSmallest(int[] pos) {
int temp;
for (int i = 0; i < pos.length; i++)
{
for (int j = i + 1; j < pos.length; j++)
{
if (pos[i] > pos[j])
{
temp = pos[i];
pos[i] =pos[j];
pos[j] = temp;
}
}
}
return pos;
}
public static int [] findBiggest(int[] pos) {
int temp;
for (int i = 0; i < pos.length; i++)
{
for (int j = i + 1; j < pos.length; j++)
{
if (pos[i] < pos[j])
{
temp = pos[i];
pos[i] =pos[j];
pos[j] = temp;
}
}
}
return pos;
}
}
Output of the position is -1 instead of the output it should give.
Thank you guys in advance :)
Arrays.asList(pos) is converting into List<int[]> convert it into List<Integer> and then get the index
List<Integer> comArray = Arrays.stream(m).boxed().collect(Collectors.toList());
System.out.println(small[0] + " at pos: " + comArray.indexOf(small[0]));
In java-7, i believe you know already how to convert int[] to List<integer>
List<Integer> comArray = new ArrayList<>();
List<Integer> intList = new ArrayList<Integer>();
for (int i : m)
{
intList.add(i);
}
Verified Code
#SuppressWarnings("unlikely-arg-type")
public static void main (String [] args) {
int m [] = {-3,23,7,12,4,-44,2,21,3,43} ;
List<Integer> comArray = Arrays.stream(m).boxed().collect(Collectors.toList());
System.out.println("Array: " + Arrays.toString(m));
int[] pos = findNumber(m);
System.out.println("Array without negatives: ");
for (int i = 0; i < pos.length; i++)
{
System.out.println(pos[i]);
}
System.out.println("Number of pos num: " + pos.length);
int sum = 0;
for (int i : pos)
sum += i;
System.out.println("Sum of pos num: " + sum);
int [] small = findSmallest(pos);
System.out.println("Smallest Number: ");
System.out.println(small[0] + " at pos: " + comArray.indexOf(small[0]));
int [] big = findBiggest(pos);
System.out.println("Biggest Number: ");
System.out.println(big[0] + " at pos: " + comArray.indexOf(big[0]));
}
public static int [] findNumber(int[] sum) {
int num = 0;
int n [] = new int [sum.length];
for(int i = 0; i < sum.length; i++)
{
if (sum[i] > 0)
{
n[num] = sum[i];
num++;
}
}
int [] pos = new int [num];
for (int k = 0 ; k < num ; k++)
{
pos[k] = n[k];
}
return pos;
}
public static int [] findSmallest(int[] pos) {
int temp;
for (int i = 0; i < pos.length; i++)
{
for (int j = i + 1; j < pos.length; j++)
{
if (pos[i] > pos[j])
{
temp = pos[i];
pos[i] =pos[j];
pos[j] = temp;
}
}
}
return pos;
}
public static int [] findBiggest(int[] pos) {
int temp;
for (int i = 0; i < pos.length; i++)
{
for (int j = i + 1; j < pos.length; j++)
{
if (pos[i] < pos[j])
{
temp = pos[i];
pos[i] =pos[j];
pos[j] = temp;
}
}
}
return pos;
}
}
Output
Array: [-3, 23, 7, 12, 4, -44, 2, 21, 3, 43]
Array without negatives:
23
7
12
4
2
21
3
43
Number of pos num: 8
Sum of pos num: 115
Smallest Number:
2 at pos: 6
Biggest Number:
43 at pos: 9
because Arrays.asList(pos) return List<int[]> not List<Integer>.

Extra line printed by bubble sort code

Writing a bubble sort algorithm in java for school and randomly getting an extra line printed to the screen, and I can't figure out why it is doing this. Here is my code.Code result here
import java.util.Scanner;
public class Assignment7 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Please enter the # of numbers to be sorted: ");
int number = input.nextInt();
System.out.print("Enter 1 for ints or 2 for doubles: ");
int intdou = input.nextInt();
if (intdou == 1) {
int x = 0;
int[] num = new int[number];
for (int q = 0; q < number; q++) {
System.out.print("Enter number: ");
num[q] = input.nextInt();
}
for (int w = 0; w < number; w++) {
for (int e = 1; e < (number - w); e++) {
if (num[e - 1] > num[e]) {
x = num[e - 1];
num[e - 1] = num[e];
num[e] = x;
for (int r = 0; r < number; r++) {
System.out.print(num[r] + ", ");
}
}
System.out.print("\n");
}
}
} else if (intdou == 2) {
double x = 0;
double[] num = new double[number];
for (int q = 0; q < number; q++) {
System.out.print("Enter number: ");
num[q] = input.nextInt();
}
for (int w = 0; w < number; w++) {
for (int e = 1; e < (number - w); e++) {
if (num[e - 1] > num[e]) {
x = num[e - 1];
num[e - 1] = num[e];
num[e] = x;
for (int r = 0; r < number; r++) {
System.out.print(num[r] + ", ");
}
}
System.out.print("\n");
}
}
}
}
}
Do you mean the extra blank line? Just move "System.out.print("\n");" inside the if block.

3rd inner while loop not working

In the blow code the inner 3rd while loop not working please tell me why ?
Here I tried with for loop by replacing the 3rd inner while loop it is working correctly but why not working with while loop .....? can you give me genuine reason...?
import java.util.Scanner;
public class MergeArray {
void arrayInitialization(Scanner arg) {
//entering test cases
System.out.println("enter test cases");
int t = arg.nextInt();
int k, l, i;
k = 0;
l = 0;
i = 0;
//outer while loop
while (t-- > 0) {
//initializing a1[]'s size
System.out.println("enter a1[]'s size");
int as1 = arg.nextInt();
int a1[] = new int[as1];
//inner while loop-1
while (as1-- > 0) {
System.out.println("enter a1[]'s elements");
a1[i] = arg.nextInt();
System.out.print(a1[i]);
i++;
}
i = 0;
//initializing a2[]'s size
System.out.println("enter a2[]'s size");
int as2 = arg.nextInt();
int a2[] = new int[as2];
//inner while loop-2
while (as2-- > 0) {
System.out.println("enter a2[]'s elements");
a2[i] = arg.nextInt();
System.out.print(a2[i]);
i++;
}
System.out.println();
int a3[] = new int[a1.length + a2.length];
int size = as1 + as2;
//inner while loop-3
while (size-- > 0) {
if (k < a1.length)
a3[l] = a1[k];
if (k < a2.length)
a3[l + 1] = a2[k];
k++;
l += 2;
}
for (int j = 0; j < (a1.length + a2.length); j++) {
System.out.print(a3[j]);
}
}
}
public static void main(String[] args) {
MergeArray ma = new MergeArray();
Scanner sc = new Scanner(System. in );
ma.arrayInitialization(sc);
}
}
I tried so much but not found solution. Here I am using while loop because I know that while loop will work fast instead of for loop.
It does not work because you are decrementing the sizes of as1 and as2. Which will be
int size = as1 + as2; // size = 0 + 0;
Instead you can make use of the array length e.g.
int size = as1.length + as2.length;
Murat K's Answer is right, but try to init the arrays like this:
//init a1
System.out.println("enter a1[]'s size");
int a1[] = new int[arg.nextInt()];
//fill a1
for (int i = 0; i < a1.length; i++) {
System.out.println("enter element " + i + " of a1[]");
a1[i] = arg.nextInt();
}
//init a2
System.out.println("enter a2[]'s size");
int a2[] = new int[arg.nextInt()];
//fill a2
for (int i = 0; i < a2.length; i++) {
System.out.println("enter element " + i + " of a2[]");
a2[i] = arg.nextInt();
}
//init a3
int a3[] = new int[a1.length + a2.length];
//merge a1 and a2 into a3
for (int i = 0; i < a1.length; i++) {
a3[i] = a1[i];
}
for (int i = 0; i < a2.length; i++) {
a3[a1.length + i] = a2[i];
}
//print
for (int i : a3) {
System.out.print(i);
}

Numbering Array items numerically

Alright, so I tried implementing the bubble sort algorithm into my code, but now my output for the second array (in my code) is giving me a ton of zeros. Can anybody tell me what is wrong with my code and how I can fix it so the zeros are removed and the only thing that remains in the output for my second array are the fixed numerically?
public static void main(String[] args) {
System.out.println("Input up to '10' numbers for current array: ");
int[] array1 = new int[10];
int i;
Scanner scan = new Scanner(System.in);
for (i = 0; i < 10; i++) {
System.out.println("Input a number for " + (i + 1) + ": ");
int input = scan.nextInt();
if (input == -9000) {
break;
} else {
array1[i] = input;
}
}
System.out.println("\n" + "Original Array: ");
for (int j = 0; j < i; j++) {
System.out.println((j + 1) + ": " + array1[j]);
}
int[] array2 = new int[i];
System.out.println("\n" + "Organized Array: ");
for (int j = 0; j < i; j++) {
int temp;
boolean organized = false;
while (organized == false) {
organized = true;
for (i = 0; i < array1.length - 1; i++) {
if (array1[i] > array1[i + 1]) {
temp = array1[i + 1];
array1[i + 1] = array1[i];
array1[i] = temp;
organized = false;
}
}
}
for (i = 0; i < array1.length; i++) {
System.out.println(array1[i]);
}
scan.close();
}
}
}
Copy your array1 to an array2 of the correct length before sorting, something like
for (i = 0; i < 10; i++) {
System.out.println("Input a number for " + (i + 1) + ": ");
int input = scan.nextInt();
if (input == -9000) {
break;
}
array1[i] = input;
}
int[] array2 = Arrays.copyOfRange(array1, 0, i);
System.out.println("Before sorting: " + Arrays.toString(array2));
Arrays.sort(array2); // <-- How I would sort.
System.out.println("After sorting: " + Arrays.toString(array2));
The reason this is necessary is because i might not be 10 in which case your array contains 0(s) to fill the other positions.
Is it possible to move all my numbers from Array 1 to Array 2 using a for-loop?
Yes. You could implement a copyOfRange function with a for loop,
private static int[] copyOfRange(int[] arr, int start, int end) {
int pos = 0;
int[] out = new int[end - start];
for (int i = start; i < end; i++) {
out[pos] = arr[i];
pos++;
}
return out;
}
the built-in version is almost certainly better.
1) You are printing the array multiple times, I think you might be giving 0 as input and thats the reason you are seeing 0's everywhere.
2) You have created array2 which is not necessary.
Move the printing logic out of for loop as in the below snippet. Otherwise your logic looks fine except fot the wrong looping of print statement.
public static void main(String args[]) {
System.out.println("Input up to '10' numbers for current array: ");
int[] array1 = new int[10];
int i;
Scanner scan = new Scanner(System.in);
for (i = 0; i < 10; i++) {
System.out.println("Input a number for " + (i + 1) + ": ");
int input = scan.nextInt();
if (input == -9000) {
break;
} else {
array1[i] = input;
}
}
System.out.println("\n" + "Original Array: ");
for (int j = 0; j < i; j++) {
System.out.println((j + 1) + ": " + array1[j]);
}
int[] array2 = new int[i];
System.out.println("\n" + "Organized Array: ");
for (int j = 0; j < i; j++) {
int temp;
boolean organized = false;
while (organized == false) {
organized = true;
for (i = 0; i < array1.length - 1; i++) {
if (array1[i] > array1[i + 1]) {
temp = array1[i + 1];
array1[i + 1] = array1[i];
array1[i] = temp;
organized = false;
}
}
}
scan.close();
}
for (i = 0; i < array1.length; i++) {
System.out.println(array1[i]);
}
}

Categories