This is my java code for array exercises at my school
and I was wondering why even though everything here works when I try to use the ImprovisedBubbleSort method my program stops functioning
public static void ImprovedBubbleSort(int [] array){
boolean swap;
int temp;
int max;
do {
swap=false;
max=1;
for (int i=0;i<array.length-max;i++){
if (array[i]>array[i+1]){
temp=array[i];
array[i]=array[i+1];
array[i+1]=temp;
swap=true;
}
max++;
}
}while (swap=true);
System.out.println("The numbers you entered in order are: ");
for (int j=0;j<10;j++){
System.out.println(array[j]);
}
}
}
It's important to realize that if you're using a single loop like in your example with that if statement you can find an instance of position 0 and 1 where it is sorted but the rest of the array may not be sorted. This will cause the if statement to not activate.
You can alleviate this problem by doing something like this:
import java.util.Arrays;
public class MyClass {
public static void main(String args[]) {
int test[] = {7,1,9,1,5,6};
bubbleSort(test);
System.out.println(Arrays.toString(test));
}
static void bubbleSort(int[] arr) {
int n = arr.length;
int temp = 0;
for(int i=0; i < n; i++){
for(int j=1; j < (n-i); j++){
if(arr[j-1] > arr[j]){
//swap elements
temp = arr[j-1];
arr[j-1] = arr[j];
arr[j] = temp;
}
}
}
}
}
See this example.
Related
Hello I am having difficulty implementing a counting sort method in java. I believe the problem comes from the last two loops I have in the method. I am getting an ArrayIndexOutOfBounds exception : 8. I believe this comes from my second to last for loop when at index 5 the value is 8 but I am not sure how to resolve this. Any help is appreciated. Thank you!
In my code k is the highest value in the input array.
Code:
public static void main(String[] args) {
int [] arrayOne = {0,1,1,3,4,5,3,0};
int [] output = Arrays.copyOf(arrayOne, arrayOne.length);
System.out.println(Arrays.toString(arrayOne));
countingSort(arrayOne, output, 5);
System.out.println(Arrays.toString(output));
}
public static void countingSort(int[] input, int[] output , int k){
int [] temp = Arrays.copyOf(input, k+1);
for (int i = 0; i <= k; i++){
temp[i] = 0;
}
for (int j = 0; j <= input.length - 1; j++){
temp[input[j]] = temp[input[j]] + 1;
}
for (int i = 1; i <= k; i++){
temp[i] = temp[i] + temp[i-1];
}
for (int j = input.length; j >= 1; j--){
output[temp[input[j]]] = input[j];
temp[input[j]] = temp[input[j]] - 1;
}
}
The problem is in the first loop because the array temp lenght is 6 and you are doing 7 interations in there.
So at the end of the for it is trying to do temp[6]=0 and the last position of your array is temp[5].
To fix this change your first loop to:
for (int i = 0; i < k; i++){
In the last loop you will get the same exception cause input[8] doesn't exist.
import java.util.Arrays;
public class CountingSort {
public static void main(String[] args) {
int[] input = {0,1,1,3,4,5,3,0};
int[] output = new int[input.length];
int k = 5; // k is the largest number in the input array
System.out.println("before sorting:");
System.out.println(Arrays.toString(input));
output = countingSort(input, output, k);
System.out.println("after sorting:");
System.out.println(Arrays.toString(output));
}
public static int[] countingSort(int[] input, int[] output, int k) {
int counter[] = new int[k + 1];
for (int i : input) { counter[i]++; }
int ndx = 0;
for (int i = 0; i < counter.length; i++) {
while (0 < counter[i]) {
output[ndx++] = i;
counter[i]--;
}
}
return output;
}
}
Above code is adapted from: http://www.java67.com/2017/06/counting-sort-in-java-example.html
this may help but try using the Arraya.sort() method.
e.g:
//A Java program to sort an array of integers in ascending order.
// A sample Java program to sort an array of integers
// using Arrays.sort(). It by default sorts in
// ascending order
import java.util.Arrays;
public class SortExample
{
public static void main(String[] args)
{
// Our arr contains 8 elements
int[] arr = {13, 7, 6, 45, 21, 9, 101, 102};
Arrays.sort(arr);
System.out.printf("Modified arr[] : %s",
Arrays.toString(arr));
}
}
example is a snippet from https://www.geeksforgeeks.org/arrays-sort-in-java-with-examples/
As per algorithm following implementation, I have prepared for the count sort technique
public static int[] countSort(int elements[]) {
int[] sorted = new int[elements.length+1];
int[] range = new int[getMax(elements)+1];
for(int i=0;i<range.length;i++) {
range[i] = getCount(i, elements);
try {
range[i] = range[i]+range[i-1];
}catch(ArrayIndexOutOfBoundsException ae) {
continue;
}
}
for(int i=0;i<elements.length;i++) {
sorted[range[elements[i]]] = elements[i];
range[elements[i]] = range[elements[i]]-1;
}
return sorted;
}
public static int getCount(int value,int[] elements) {
int count = 0;
for(int element:elements) {
if(element==value) count++;
}
return count;
}
public static int getMax(int elements[]) {
int max = elements[0];
for(int i=0;i<elements.length;i++) {
if(max<elements[i]) {
max = elements[i];
}
}
return max;
}
Please review and let me know if any feedback and it is more helpful.
Note :
Non-negative no won't support in the above implementation.
don't use 0th index of the sorted array.
I want to separate negative numbers and positive numbers in an array.
For example, if my array has 10 values and they are {-8,7,3,-1,0,2,-2,4,-6,7}, I want the new modified array to be {-6,-2,-1,-8,7,3,0,2,4,7}.
I want to do this in O(n^2) and I have written a code as well. But I am not getting the right outputs. Where is my code wrong?
import java.util.Random;
public class Apples {
public static void main(String[] args) {
Random randomInteger=new Random();
int[] a=new int[100];
for(int i=0;i<a.length;i++)
{
a[i]=randomInteger.nextInt((int)System.currentTimeMillis())%20 - 10;
}
for(int i=0;i<a.length;i++)
{
if(a[i]<0)
{
int temp=a[i];
for(int j=i;j>0;j--)
{
a[j]=a[j-1];
j--;
}
a[0]=temp;
}
}
for(int i=0;i<a.length;i++)
{
System.out.print(a[i]+" ");
}
}
}
You have two j-- while you need only one, so remove either one of them.
for(int j=i;j>0;j--)
{
a[j]=a[j-1];
// remove j--; from here
}
You might consider the following as an alternative way of doing the partition of negatives/positives. This is based on K&R's quicksort, but only makes one pass on the array:
import java.util.Random;
public class Sweeper {
public static void printArray(int[] a) {
for (int elt : a) {
System.out.print(elt + " ");
}
System.out.println();
}
public static void swap(int[] a, int i, int j) {
int tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
public static void partition(int[] a, int target) {
int last = 0;
for (int i = 0; i < a.length; ++i) {
if (a[i] < target && i != last) swap(a, i, last++);
}
}
public static void main(String[] args) {
Random rng = new Random();
int[] a = new int[20];
for (int i = 0; i < a.length; i++) {
a[i] = rng.nextInt(20) - 10;
}
printArray(a);
partition(a, 0);
printArray(a);
}
}
I have created my version of the merge sort algorithm in java code. My issues are these: when I run the code as is, I get a NullPointerExecpetion in the main on line 27 (see commented line). And I know there is way to make the method calls and instantiate newArray without them being static but Im not quite sure how.. can someone help fix these? I am still relatively new to java so be nice :)
Main:
import java.util.Random;
public class MergeSort_main
{
public static void main(String[] args)
{
int[] originalArray = new int[1000];
Random rand = new Random();
for (int i = 0; i < originalArray.length; i++)
{
int randNum = rand.nextInt(1000)+1;
originalArray[i] = randNum;
}
for(int i = 0; i < originalArray.length; i++)
{
System.out.println(i+"." + originalArray[i]);
}
System.out.println("---------------------End Random Array-------\n");
MergeSortAlgorithm.mergeSortAlg(originalArray);
int[] sortedArray = MergeSortAlgorithm.getSortedArray();
for(int i = 0; i < sortedArray.length; i++) //NULL POINTER EXCEPTION HERE
{
System.out.println(i+ "." + sortedArray[i]);
}
}
}
Algorithm Class:
public class MergeSortAlgorithm
{
private static int[] newArray;
public static void mergeSortAlg(int[] randomNums)
{
int size = randomNums.length;
if (size < 2)
{
return; //if the array can not be split up further, stop attempting to split.
}
int half = size / 2;
int firstHalfNums = half;
int secondHalfNums = size - half;
int[] firstArray = new int[firstHalfNums];
int[] secondArray = new int[secondHalfNums];
for (int i = 0; i < half; i++)
{
firstArray[i] = randomNums[i];
}
for (int i = half; i < size; i++)
{
secondArray[i - half] = randomNums[i];
}
mergeSortAlg(firstArray);
mergeSortAlg(secondArray);
merge(firstArray, secondArray, randomNums);
}
public static void merge(int[] firstArray, int[] secondArray, int[] newArray)
{
int firstHalfNums = firstArray.length;
int secondHalfNums = secondArray.length;
int i = 0; //iterator for firstArray
int j = 0; //iterator for second array
int k = 0; //interator for randomNums array
while (i < firstHalfNums && j < secondHalfNums)
{
if (firstArray[i] <= secondArray[j])
{
newArray[k] = firstArray[i];
i++;
k++;
}
else
{
newArray[k] = secondArray[j];
k++;
j++;
}
}
while (i < firstHalfNums)
{
newArray[k] = firstArray[i];
k++;
i++;
}
while (j < firstHalfNums)
{
newArray[k] = secondArray[j];
k++;
j++;
}
}
public static int[] getSortedArray()
{
return newArray;
}
}
Basically, the only problem with your code is that you don't initialize newArray with any values, resulting in a null.
You are also redefining newArray at the top of your merge function .
The problem is that newArray[] is never instantiated i.e. newArray reference is pointing to null. And, no change is made in the newArray so value or reference returned to main is null. And, then you are performing sortedArray.length where sorted array having a null value.
You have to make newArray[] point to randomNums[].
This is the code I have for my selection sort program, I want to know if there's any way of improving the code without using additional methods or classes.
public class Selection_Sort {
public static void main(String[] args) {
int arr[]={234,151,123,4,5342,76,48};
int min=0; int temp;
for(int i=0;i<=arr.length-1;i++){
min=i;
for (int k=i+1;k<arr.length;k++){
if(arr[k]<arr[i]){
temp=arr[i];
arr[i]=arr[k];
arr[k]=temp;
}
}
}
for (int j=0;j<=arr.length-1;j++)
System.out.println(arr[j]+" ");
}
}
public static void main(String[] args) {
int arr[]={234,151,123,4,5342,76,48};
int arrLength = arr.length;
for(int i=0;i<arrLength-1;i++){
int min=i;
for (int k=i+1;k<arrLength;k++){
if(arr[k]<arr[min]){
min = k;
}
}
if (i != min) {
int temp=arr[i];
arr[i]=arr[min];
arr[min]=temp;
}
}
for (int j=0;j<arrLength;j++) {
System.out.println(arr[j]+" ");
}
}
Looks like you are using the bubblesort algorithm which is very slow. If you want to improve your code, i would recommend to use an algorithm like ripplesort or quicksort.
Slight improvement should be like this :
int arrayLength = arr.length;
// Then use it in conditional statement of for loop.
So that it won't invoke length property of Array every time in loop. For small number of loops it doesn't impact much but it will help to reduce the time when loops are more or number of iteration of loop are more.
The value of the local variable min is not used
k <= arr.length-1
-->
k < arr.length
Use this
class Selection {
public static void main(String[] args) {
int arr[]={234,151,123,4,5342,76,48}; /* arr[0] to arr[n-1] is the array to sort */
int lowest, i, j;
for(i = 0 ; i < arr.length-1; i++) { /* advance the position through the entire array */
lowest = i; /* assume the min is the first element */
for(j = i+1 ; j < arr.length; j++) { /* if this element is less, then it is the new minimum */
if(arr[j] < arr[lowest]) {
lowest = j; /* found new minimum; remember its index */
}
}
if(lowest != i) { /* lowest is the index of the minimum element. Swap it with the current position */
int temp = arr[i];
arr[i] = arr[lowest];
arr[lowest] = temp;
}
}
for (int k = 0; k <= arr.length-1 ; k++) {
System.out.println(arr[k] + " ");
}
}
}
This is the selection sort algorithm you asked.
Here is original Selection sort implementation. The implementation in question in not using min to perform the swap operation.
public static void sort(int[] arr) {
int min=-1;
for (int i = 0; i < arr.length; i++) {
min = i;
for (int j = i + 1; j < arr.length; j++) {
if (arr[min] > arr[j]) {
min = j;
}
}
if (min != i) {
int temp = arr[min];
arr[min] = arr[i];
arr[i] = temp;
}
}
}
public class JavaApplication55 {
public static void main(String[] args) {
int[] array ={234,435,567,768,123,456,789,789,5670,6789};
for(int j =0;j< array.length;j++){
for(int i =j+1;i < array.length;i++ ){
int temp;
if(array[j]>array[i]){
temp =array[j];
array[j] =array[i];
array[i] =temp;
}
else{}
}}
for(int k =0;k< array.length;k++){
System.out.println(array[k]);
}
}
enter code here
}
class arrayDemo {
static void sort2D(int[][] B) {
boolean swap = true;
int oy=0;
int temp=0;
for(int ox=0;ox<B.length;ox++){
while(oy<B[ox].length) {
while(swap) {
swap = false;
for(int ix=0;ix<B.length;ix++) {
for(int iy=0;iy<B[ix].length;iy++) {
if(B[ox][oy]<B[ix][iy]) {
temp = B[ix][iy];
B[ix][iy] = B[ox][oy];
B[ox][oy] = temp;
swap = true;
}
}
}
}
oy++;
}
}
for(int row=0;row<B.length;row++)
for(int col=0;col<B[row].length;col++)
System.out.println(B[row][col]);
}
public static void main(String...S) {
int y[][] = {{10,20,0,30},{10,5,8},{3,9,8,7},{2,3}};
sort2D(y);
}
}
I am trying to sort a 2D array in ascending order.
Input: {{10,20,0,30},{10,5,8},{3,9,8,7},{2,3}};
Output: 30,20,10,10,9,8,8,7,5,3,0,2,3
Can someone help me know what is wrong with my code.
You are comparing elements that are not in the same row or column. Each sub-array should be sorted individually. You might want to reconsider this line if (B[ox][oy] < B[ix][iy]).
That code has a number of problems.
It throws ArrayIndexOutOfBoundsException. This is because all for loop tests test against B.length, which is not correct for inner arrays.
You are comparing every pair of elements, but some pairs are the reverse of other pairs, and the reverse pairs should not be tested. You need to limit the scope of your inner set of for loops, by starting at a different index.
To fix all these problems, the path of least resistance is to dump the 2D array into a 1D array and sort that, which is much easier.
Here is code that has been tested and shown to work:
static void sort2D(int[][] B) {
int count = 0;
for (int[] is : B)
for (int i : is)
count++;
int[] A = new int[count];
count = 0;
for (int[] is : B)
for (int i : is)
A[count++] = i;
int temp;
for (int i = 0; i < A.length; i++)
for (int j = i + 1; j < A.length; j++)
if (A[i] > A[j]) {
temp = A[i];
A[i] = A[j];
A[j] = temp;
}
for (int i = 0; i < A.length; i++)
System.out.print(A[i] + ",");
}