I've attempted to code an Insertion Sort in java via pseudo code from a book. The output for this code should be numbers in ascending order but for some reason I get 10,4,5,6,7,8,9. Any help is greatly appreciated! Thanks!
public class InsertionSort {
public int Array[] = {10,9,8,7,6,5,4};
public static void main(String[] args) {
InsertionSort obj1 = new InsertionSort();
}
public InsertionSort() {
InsertionSortMethod();
PrintArray();
}
public void InsertionSortMethod() {
for(int j = 2; j < Array.length; j++) {
int key = Array[j];
int i = j - 1;
while(i > 0 && Array[i] > key) {
Array[i + 1] = Array[i];
i = i - 1;
}
Array[i + 1] = key;
}
}
public void PrintArray() {
for(int i = 0; i < Array.length; i++) {
System.out.println(Array[i]);
}
}
}
Start the for loop from j=1 like this :
for(int j = 1; j < array.length; j++) {
and modify while loop condition like this:
while(i >= 0 && array[i] > key) {
Correct working code :
public class InsertionSort {
public int array[] = {10,9,8,7,6,5,4};
public static void main(String[] args) {
InsertionSort obj = new InsertionSort();
obj.insertionSortMethod();
obj.printArray();
}
public void insertionSortMethod() {
for(int j = 1; j < array.length; j++) {
int key = array[j];
int i = j - 1;
while(i >= 0 && array[i] > key) {
array[i + 1] = array[i];
i = i - 1;
}
array[i + 1] = key;
}
}
public void printArray() {
for(int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
}
}
At the third line of your code i.e.,
InsertionSort obj1 = new InsertionSort();
You are making an object of InsertionSort class but in your code, it is defined as a function I think it is a constructor you must mention the class for more convenience of the reader.
Apart from that, you are starting your loop with 2 for(int j = 2; j < Array.length; j++)
why so? your one element got missed so start j with 1
:)
Thanks to all the answers. I have also found by tracing the algorithm that flipping the second 'greater than' sign to a 'less than' sign on the 5th line of the algorithm does the trick for working in descending order. This may possibly be a typo in the book i'm reading. Thanks again!
try this method
public int[] insertionSort(int[] list) {
int i, j, key, temp;
for (i = 1; i < list.length; i++) {
key = list[i];
j = i - 1;
while (j >= 0 && key < list[j]) {
temp = list[j];
list[j] = list[j + 1];
list[j + 1] = temp;
j--;
}
}
return list;
}
package com.borntoinnovation.datastructure;
import java.util.Arrays;
public class SortingInsertion {
public static void main(String[] args) {
int[] array = new int[] { 4, 3, 2, 20, 12, 1, 5, 6 };
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < i; j++) {
if (array[i] < array[j]) {
int temp = array[i];
for (int k = i; k > j; k--) {
array[k] = array[k - 1];
}
array[j] = temp;
}
}
System.out.println(Arrays.toString(array));
}
}// end of main()
}
Related
So I'm trying to create Bubble and Selection sort and this is the code I have so far.
package club.westcs.javabasics;
import java.util.ArrayList;
import java.util.Collections;
public class SortsRunner {
public static void BubbleSort(ArrayList<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;
}
}
}
public static void SelectionSort(ArrayList<Integer> nums) {
int n = nums.size();
for (int i = 0; i < n-1; i++)
{
int min_idx = i;
for (int j = i+1; j < n; j++)
if (nums.get(j) < nums.get(min_idx))
min_idx = j;
int temp = nums.get(min_idx);
nums.set(j, nums.get(j+1)) = nums.set(i);
nums.set(i, min_idx) = temp;
}
}
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());
}
}
My selection sort is erroring for nums.set(j, nums.get(j+1)) = nums.set(i); and nums.set(i, min_idx) = temp; I want this portion of the code to swap the minimum element with the first element. I'm not sure how to do it correctly with the ArrayList stuff. Could someone give me some tips?
You are getting a compilation error because it is impossible to use '=' operator for void functions (such as nums.set(j, nums.get(j+1))). Setters are always void and you cannot assign smth to nothing!
The signature of ArrayList setter looks like:
public E set(int index, E element)
where first parameter is index of the array (0, 2, 3 ... N), second is a value you want to set under this index.
By the way your selection sort looks strange.
Try this code:
public static void doSelectionSort(ArrayList<Integer> arr) {
for (int i = 0; i < arr.size(); i++) {
// find position of smallest num between (i + 1)th element and last element
int pos = i;
for (int j = i; j < arr.size(); j++) {
if (arr.get(j) < arr.get(pos))
pos = j;
}
// Swap min (smallest num) to current position on array
int min = arr.get(pos);
arr.set(pos, arr.get(i));
arr.set(i, min);
printOut(i + 1, arr);
}
}
I've written this to sort two arrays and then compare the values to see if they're the same, but it always returns false, and I can't figure out why.
It is supposed to find if two arrays are permutations of each other.
public class Permutations {
public static void main(String[] args) {
int[] a = {1,4,6,7,8,34};
int[] b = {34,6,8,1,4,7};
System.out.println(arePermutations(a, b));
}
public static boolean arePermutations(int[] a, int[] b)
{
int count = 0;
int temp = 0;
if(a.length == b.length)
{
for(int i=0; i<a.length-1; i++)
for(int j=0; j<a.length-1; j++)
if(a[i] > a[j+1] && i>j+1)
{
temp = a[i];
a[i] = a[j+1];
a[j+1] = temp;
}
{
for(int i=0; i<b.length-1; i++)
for(int j=0; j<b.length-1; j++)
if(b[i] > b[j+1] && i>j+1)
{
temp = b[i];
b[i] = b[j+1];
b[j+1] = temp;
}
}
for(int i=0; i<a.length; i++)
if(a[i] == b[i])
{
count++;
}
if (count == a.length)
{
return true;
}
else return false;
}
else return false;
}
}
The problem is in the implementation of the bubble sort. Change your sorting loops to the following:
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a.length - 1; j++) {
if (a[j] > a[j + 1]) {
temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
}
for (int i = 0; i < b.length; i++) {
for (int j = 0; j < b.length - 1; j++) {
if (b[j] > b[j + 1]) {
temp = b[j];
b[j] = b[j + 1];
b[j + 1] = temp;
}
}
}
This code works because a bubble sort just swaps adjacent elements if they need swapping, but needs to run through the entire array multiple times (up to the number of items in the array) to get all the items into the correct position.
My task is to write a function that rearranges an array so that the odd numbers occur in the beginning of the array, from greatest to least, and the even numbers from least to greatest at the end. We are not allowed to use any other libraries except for the standard input and output streams.
The output works when the numbers are:
{-15, 450, 6, -9, 54}
But if I changed the elements to:
{-55, 45, 6, 11, 54}
There is an exception error. Here is my code:
public class ary1 {
public static void sort(int A[], int n) {
int tmp;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (A[0] % 2 == 0) //even
{
if (A[i] < A[j]) {
tmp = A[i];
A[i] = A[j];
A[j] = tmp;
}
} else {
if (A[i] > A[j]) {
tmp = A[i];
A[i] = A[j];
A[j] = tmp;
}
}
}
}
}
public static void showAray(int A[], int n) {
for (int i = 0; i < n; i++) {
System.out.println(A[i]);
}
}
public static void main(String args[]) {
int array1[] = {-55, 45, 6, 11, 54};
int odd = 0;
int even = 0;
for (int i = 0; i < array1.length; i++) {
if (array1[i] % 2 == 0) {
even++;
} else {
odd++;
}
}
int[] array2 = new int[even];
int[] array3 = new int[odd];
for (int i = 0, j = 0, k = 0; i < array1.length; i++) {
if (array1[i] % 2 == 0) {
array2[j++] = array1[i];
} else {
array3[k++] = array1[i];
}
}
System.out.println("Original array:\n");
showAray(array1, array1.length);
sort(array2, even);
sort(array3, odd);
for (int i = 1; i < array1.length; i++) {
if (i < odd) {
array1[i] = array3[i];
} else {
array1[i] = array2[(i + 1) - even];
}
}
System.out.println("\nAfter sorting:\n");
showAray(array1, array1.length);
}
}
I know there is a logical error here, but I can't figure out what exactly. Is there any way to change the logic to work with all integers? Thanks.
array1[i] = array2[(i + 1) - even];
EDIT - Here is the stacktrace.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
at ary.main(arytest.java:67)
Java Result: 1
Change this
array1[i] = array2[(i + 1) - even];
to
array1[i] = array2[i - odd];
I guess this is what you want
I am just sorting an array and need some advice on the sorting and I also need help printing the array after I have sorted it. Also no, I do not want to use the Arrays utility.
Code:
package Sort;
public class SortCode {
static int[] intArray = {
12, 34, 99, 1, 89,
39, 17, 8, 72, 68};
int j = 0;
int i = 0;
void printArray(int[] arrayInts) {
System.out.println("Values before sorting:");
System.out.println("Index" + "\tValue");
for (; j < arrayInts.length; j++) {
System.out.println(j + "\t" + arrayInts[j]);
} //for (int j)
} //void printArray
void sortArray() {
System.out.println("Values after sorting:");
System.out.println("Index" + "\tValue");
int i;
int k;
for (i = 0; i < intArray.length; i++) {
for (k = 0; k > intArray.length; k++) {
if (intArray[i] > intArray[k]) {
int firstNum = intArray[i];
int secondNum = intArray[k];
intArray[i] = secondNum;
intArray[k] = firstNum;
} //if
} //for
} //for
} //void sortArray
} //class BranchCode
Change sign > for < inside for (k = 0; k > intArray.length; k++) {
Probably it should help you
You would be able to find different sorting implementation on mathbits http://mathbits.com/MathBits/Java/arrays/Sorting.htm .
Here is better example of bubble sort .
public void bubbleSort(int[] array) {
boolean swapped = true;
int j = 0;
int tmp;
while (swapped) {
swapped = false;
j++;
for (int i = 0; i < array.length - j; i++) {
if (array[i] > array[i + 1]) {
tmp = array[i];
array[i] = array[i + 1];
array[i + 1] = tmp;
swapped = true;
}
}
}
}
This might help as well Java: Sort an array
Example to use code
public class SortExample {
int[] intArray = { 12, 34, 99, 1, 89, 39, 17, 8, 72, 68 };
public void printArray(int[] arrayInts) {
for (int j = 0; j < arrayInts.length; j++) {
System.out.println(j + "\t" + arrayInts[j]);
} // for (int j)
} // void printArray
public void bubbleSort(int[] array) {
boolean swapped = true;
int j = 0;
int tmp;
while (swapped) {
swapped = false;
j++;
for (int i = 0; i < array.length - j; i++) {
if (array[i] > array[i + 1]) {
tmp = array[i];
array[i] = array[i + 1];
array[i + 1] = tmp;
swapped = true;
}
}
}
}
public void process() {
System.out.println("Values before sorting:");
System.out.println("Index \tValue");
printArray(intArray);
bubbleSort(intArray);
System.out.println("Values after sorting:");
System.out.println("Index" + "\tValue");
printArray(intArray);
}
public static void main(String[] args) {
SortExample example = new SortExample();
example.process();
}
}
I'm having trouble using insertion to sort an array of strings.
When I compile the following code:
public class Project1 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String names[]=new String[5];
int size=names.length;
System.out.println("Enter the 5 car manufacturers: ");
//Load Array
for (int i = 0; i < 5; i++) {
names[i] = input.nextLine();
}
//Print descending order list
String[] descSort;
descSort=bubbleSortDesc(names);
System.out.println("Car manufacturers listed sorted in descending order (via BubbleSort): ");
for (int x=0; x < names.length; x++) {
System.out.println(names[x]);
}
//Print ascending order list
insertionSortAsc(names, size);
System.out.println("Car manufacturers listed sorted in ascending order (via InsertionSort): ");
for (int z=0; z < names.length; z++) {
System.out.println(names[z]);
}
}ยจ
public static String[] bubbleSortDesc(String[] names) {
String temp;
int passNum, i, result;
for (passNum=1; passNum <= 4; passNum++) {
for (i = 0; i<=(4-passNum); i++) {
result=names[i].compareToIgnoreCase(names[i+1]);
if(result<0) {
temp=names[i];
names[i]=names[i+1];
names[i+1]=temp;
}
}
}
return names;
}
public static void insertionSortAsc(String[] names, int i) {
String temp = names[i];
int j = i-1;
while (j >= 0 && names[j].compareToIgnoreCase(temp) > 0) {
names[j+1]=names[j];
j--;
}
names[j+1]=temp;
}
public static void insertionSort(String[] names, int n) {
for(int i = 1; i<n; i++) {
insertionSortAsc(names, i);
}
}
}
It gives me the error:
cannot find symbol- method insert(java.lang.String[], int)
I suspect it has something to do with the fact that we were told to use our book as reference for the code, yet the book only deals with sorting data of type int and there are no examples for sorting string data.
Any help is appreciated.
Edit: After fixing the error, the program compiles and executes but after inputting the data it crashes and gives me the following error
java.lang.ArrayIndexOutofBoundsException:
5
This error highlights the line String temp = names[i]
You haven't defined a method named insert.
This will work the way you intend:
public static void insertionSortAsc(String[] names, int n)
{
for(int i = 1; i<n; i++)
{
insert(names, i);
}
}
public static void insert(String[] names, int i)
{
String temp = names[i];
int j = i - 1;
while (j >= 0 && names[j].compareToIgnoreCase(temp) > 0)
{
names[j + 1]= names[j];
j--;
}
names[j + 1] = temp;
}
public static void insertionSort(int... arr) {
for (int i = 1; i < arr.length; i++) {
if (arr[i] >= arr[i - 1])
continue;
int j = i - 1;
for (; j >= 0; j--)
if (arr[j] < arr[i])
break;
int tmp = arr[i];
System.arraycopy(arr, j + 1, arr, j + 2, i - j - 1);
arr[j + 1] = tmp;
}
}