Sorting an Array in Java, then printing it - java

I have an error in my code, since it is not printing all of the elements of the array after it's been sorted. Can someone spot it and help me out? (I am only in my 5th week of Java, so definitely a newbie!)
public class Test01 {
public static void main(String[] args) {
int[] arr = {1, 3, 5, 4, 2};
for (int i = 0; i < arr.length - 1; i++) {
int currentMin = arr[i];
int currentMinIndex = i;
for (int j = i + 1; j < arr.length; j++) {
if (currentMin > arr[j]){
currentMin = arr[j];
currentMinIndex = j;
}
}
if (currentMinIndex != i) {
arr[currentMinIndex] = arr[i];
arr[i] = currentMin;
}
System.out.print(arr[i] + " ");
}
}
}
The current output for this is:
1 2 3 4
So I am just missing printing the '5'
thanks for the help!

You are running the loop an index short. Change
for (int i = 0; i < arr.length - 1; i++) { // The -1 is the issue
to
for (int i = 0; i < arr.length ; i++) {

public class Test01 {
public static void main(String[] args) {
int[] arr = {1, 3, 5, 4, 2};
for (int i = 0; i < arr.length; i++) {
int currentMin = arr[i];
int currentMinIndex = i;
for (int j = i + 1; j < arr.length; j++) {
if (currentMin > arr[j]){
currentMin = arr[j];
currentMinIndex = j;
}
}
if (currentMinIndex != i) {
arr[currentMinIndex] = arr[i];
arr[i] = currentMin;
}
System.out.print(arr[i] + " ");
}
}
}

Related

how can fix the error in this code and how can change from for loop to recursion ? i'm beginner in programming :)

i try to make method that can be find the profit for some input and calculation.
but i think there a problem in a length of Array or somewhat i don't know.
also i wanna try it by using recursive but how to implement ?
please i need your helps ^_^
thanks
public class MatlabLAB2 {
public static void main(String[] args) {
int capital = 100;
int nDay = 7;
int[] buyP = {5, 20, 7, 10, 4, 80, 1};
int[] sellP = {25, 50, 100, 3, 10, 2, 95};
findProfit(capital, nDay, buyP, sellP);
}
public static void findProfit(int capital, int NDay, int[] BuyingP, int[] SellingP) {
int[] Array = new int[NDay];
int Profit = 0;
for (int i = 0; i <= BuyingP.length; i++) {
for (int j = i; j <= SellingP.length; j++) {
for (int k = 0; k <= NDay-1; k++) {
Array[k] = (capital / BuyingP[i]) * SellingP[j];
}
Profit = findMaxOfArray(Array);
}
}
System.out.println(Profit);
}
public static int findMaxOfArray(int[] a) {
int max = 0;
for (int i = 0; i <= a.length-1; i++) {
if (a[i] >= max) {
max = a[i];
}
}
return max;
}
}
the result:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7
at matlab.lab.pkg2.MatlabLAB2.findProfit(MatlabLAB2.java:24)
at matlab.lab.pkg2.MatlabLAB2.main(MatlabLAB2.java:11)
Java Result: 1
You are iterating the loop till
(int i = 0; i <= BuyingP.length; i++)
it should be iterated till
(int i = 0; i < BuyingP.length; i++)
same with j loop
You have two options to fix this.
1.
public static void findProfit(int capital, int NDay, int[] BuyingP, int[] SellingP) {
int[] Array = new int[NDay];
int Profit = 0;
for (int i = 0; i <= BuyingP.length-1; i++) {
for (int j = i; j <= SellingP.length-1; j++) {
for (int k = 0; k <= NDay-1; k++) {
Array[k] = (capital / BuyingP[i]) * SellingP[j];
}
Profit = findMaxOfArray(Array);
}
}
System.out.println(Profit);
}
2.
public static void findProfit(int capital, int NDay, int[] BuyingP, int[] SellingP) {
int[] Array = new int[NDay];
int Profit = 0;
for (int i = 0; i < BuyingP.length; i++) {
for (int j = i; j < SellingP.length; j++) {
for (int k = 0; k <= NDay-1; k++) {
Array[k] = (capital / BuyingP[i]) * SellingP[j];
}
Profit = findMaxOfArray(Array);
}
}
System.out.println(Profit);
}
Because in your code your array goes from 0 to 6 and you are trying to take array[7] which is out of your array's bound.

How to shift elements to left after removing array element?

I was asked to write, to remove the element (lets say k=30) from the array and shift the other elements to its left without using inbuilt methods.
I have tried the below approach.
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] arr = new int[] { 1, 2, 30, 4, 5, 30, 6 };
int k = 30;
int count = 0;
System.out.println("---Original Array------");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
for (int i = 0; i < arr.length; i++) {
if (arr[i] == k)
count++;
}
for (int j = 0; j < count; j++) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] == k) {
for (int l = i; l < arr.length - 1; l++) {
arr[l] = arr[l + 1];
}
}
}
}
System.out.println("---Modified Array------");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
I need output like this: [1 2 4 5 6 0 0]
But the output from the above logic is: [1 2 4 5 6 6 6]
Also, I'm worried about using nested for loops here. Is there any way that we can reduce the time complexity with out using any inbuilt methods?
Here is another variant:
int[] arr = new int[] { 1, 2, 30, 4, 5, 30, 6 };
int k = 30;
int j = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] != k) {
arr[j++] = arr[i];
}
}
while (j < arr.length) {
arr[j++] = 0;
}
In order to not change your approach drastically, I would suggest adding another iteration of the array at the end, to insert 0s to count-many indices from the end of your array.
This would be as simple as adding the following snippet:
// nested for loop
// ...
// set trailing elements to 0s
for (int i = 0; i < count ; i++)
arr[arr.length-1-i] = 0;
System.out.println("\n---Modified Array------");
// ...
There are some cleaner/more-efficient ways of solving this problem.
Based exactly on your approach, I went ahead and made a modification to your nested loop to not require another iteration.
for (int j = 0; j < count; j++) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] == k) {
for (int l = i; l < arr.length - 1; l++)
arr[l] = arr[l + 1];
// since we have performed the shifting, we can safely set the last element to 0
arr[arr.length-1] = 0; // <----- this was missing!!
}
}
}
The following code gives the desired result:
int [] arr = { 1, 2, 30, 4, 5, 30, 6 };
int k = 30;
int elementCount = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] == k) {
++elementCount;
}
}
int count = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] == k) {
count++;
for (int j = i; j < arr.length-1; j++) {
arr[j] = arr[j+1];
}
arr[arr.length-1] = 0;
}
if (count == elementCount) {
break;
}
}
I don't know if it helps. This is a simplified aproach, that is easier to read and understand(at least for people that learned C), that does removal as required....
public static void main(String[] args) {
int[] arr = new int[] { 1, 2, 30, 4, 5, 30, 6 };
int k = 30;
int i=0;
int j=0;
for(;j<arr.length;i++,j++){
if((arr[i]=arr[j])==k) i--;
}
while(i<j)arr[i++]=0;
System.err.println(Arrays.toString(arr));
}
output:[1, 2, 4, 5, 6, 0, 0]
First version with a small fix on your code. You issue is that the shifted elements need to be replaced by zero. Which require basically an if statement with the arr.length - count
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] arr = new int[] { 1, 2, 30, 4, 5, 30, 6 };
int k = 30;
int count = 0;
System.out.println("---Original Array------");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println("");
for (int i = 0; i < arr.length; i++) {
if (arr[i] == k)
count++;
}
for (int j = 0; j < count; j++) {
for (int i = 0; i < arr.length; i++) {
if(i >= arr.length - count){
arr[i] = 0;
}else {
if (arr[i] == k) {
for (int l = i; l < arr.length - 1; l++) {
arr[l] = arr[l + 1];
}
}
}
}
}
System.out.println("---Modified Array------");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println("");
}
Which gives output
---Original Array------
1 2 30 4 5 30 6
---Modified Array------
1 2 4 5 6 0 0
Now, we can simplify the code also
public static void main(String[] args) {
int[] arr = new int[] { 1, 2, 30, 4, 5, 30, 6 };
int k = 30;
int count = 0;
System.out.println("---Original Array------");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println("");
for(int i = 0; i < arr.length; i++){
if(arr[i]==k){
count++;
}else{
arr[i-count] = arr[i];
}
}
for(int i = 1; i <= count; i++){
arr[arr.length - i] = 0;
}
System.out.println("---Modified Array------");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println("");
}
which give the same output

Is my bubble sort and selection sort properly implemented?

Here is what I have for the bubble sort algorithm.
public void bubbleSort(int[] arr) {
boolean swapped = true;
int j = 0;
temp = 0;
while(swapped) {
swapped = false;
j++;
for(int i = 0; i < arr.length; i++) {
if (arr[i] > arr[i + 1]) {
temp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = temp;
swapped = true;
}
}
}
}
And for selection sort:
public int[] selectionSort(int[] arr) {
int i = 0;
int j = 0;
int minValue = 0;
int minIndex = 0;
int temp = 0;
for(i = 0; i < arr.length - j; j++) {
minValue = arr[i];
minIndex = i;
for(j = i; i < arr.length; j++) {
if (minValue < arr[i]) {
minValue = arr[j];
minIndex = j;
}
}
if (minValue < arr[i]) {
temp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = temp;
}
}
return arr;
}
Not sure about these implementations.
When I add a System.out.println(arr[i]); in there the numbers for bubble sort come out as:
4
3
2
1
3
2
1
2
1
1
[I#6d06d69c
When put at after the first if statement.
Now when I create a System.out.println(arr[i]); for selection sort it comes out as:
1
2
3
4
5
[I#6d06d69c
When put after the second if statement.
Thank you
There are a few bugs in your implementations which I have tried to correct.
public void bubbleSort(int[] arr) {
boolean swapped = true;
int j = 0;
temp = 0;
while(swapped) {
swapped = false;
j++;
for(int i = 0; i < arr.length-j; i++) {
if (arr[i] > arr[i + 1]) {
temp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = temp;
swapped = true;
}
}
}
}
public int[] selectionSort(int[] arr) {
int i = 0;
int j = 0;
int minValue = 0;
int minIndex = 0;
int temp = 0;
for(i = 0; i < arr.length - 1; i++) {
minValue = arr[i];
minIndex = i;
for(j = i+1; j < arr.length; j++) {
if (minValue < arr[j]) {
minValue = arr[j];
minIndex = j;
}
}
if (minValue < arr[i]) {
temp = arr[i];
arr[i] = minValue;
arr[minIndex] = temp;
}
}
return arr;
}

How to do selection sorting in Java?

Here is the my code for a project I am working on for class:
import java.lang.reflect.Array;
public class Project10_MaryEvans {
public static void main(String[] args) {
int[] numbers = {2, 7, 5, 3, 4, 9, 8, 10, 1, 6};
int i = 0;
final int NUMBERS_SIZE = 10;
System.out.print("Unsorted: ");
for (i = 0; i < NUMBERS_SIZE; ++i){
System.out.print(numbers[i] + " ");{
System.out.println();
}
sorting(numbers, NUMBERS_SIZE);
System.out.print("Sorted: ");
for(i = 0; i < NUMBERS_SIZE; ++i){
System.out.print(numbers[i] + " ");
}
System.out.println();
return;
}
}
public static int[] shuffle(int[] numbers){
for(int i = 0; i < numbers.length; ++i) {
numbers[i] = (int)Math.random() * numbers[i];
}
return numbers;
}
public static void sorting(int[] numbers, int numberSize) {
int i = 0;
int j = 0;
int indexSmallest = 0;
int temp = 0;
for (i = 0; i < numberSize; ++i) {
indexSmallest = i;
for(j = i + 1; j < numberSize; ++j) {
if(numbers[j] < numbers[indexSmallest]) {
indexSmallest = j;
}
}
}
}
}
I am not getting the correct output. My output is:
Unsorted: 2
Sorted: 2 7 5 3 4 9 8 10 1 6
I'm juste gonna give you tips here:
Use Arrays.toString(numbers) to print your array easily.
Use numbers.length to get the size of the numbers array.
(the most important one) Your sorting doesn't actually do any sorting, you just set indexes values, but you don't modify the array numbers (numbers[i] = numbers[j] for example).
Your first loop (in main) is useless.
And read the comments.
maybe you have make two for loop nested in your main function, it should be like
System.out.print("Unsorted: ");
for (i = 0; i < NUMBERS_SIZE; ++i){
System.out.print(numbers[i] + " ");
}
System.out.println();
sorting(numbers, NUMBERS_SIZE);
System.out.print("Sorted: ");
for(i = 0; i < NUMBERS_SIZE; ++i){
System.out.print(numbers[i] + " ");
}
System.out.println();
return;
In your sorting function you're forgetting to exchange current element with the minimal found. You're just computing indexes.
Use this method for sorting. Not need int numberSize parameter. It can get through array length. If you need int numberSize parameter replace numbers.length with numberSize.
public static void sorting(int[] numbers) {
int temp;
for (int i = 0; i < numbers.length; i++) {
for (int j = i + 1; j < numbers.length; j++) {
if (numbers[i] > numbers[j]) {
temp = numbers[i];
numbers[i] = numbers[j];
numbers[j] = temp;
}
}
}
}
Main Method:
public static void main(String[] args) {
int[] numbers = {2, 7, 5, 3, 4, 9, 8, 10, 1, 6};
int i = 0;
final int NUMBERS_SIZE = 10;
System.out.print("Unsorted: ");
for (i = 0; i < NUMBERS_SIZE; ++i){
System.out.print(numbers[i] + " ");
}
System.out.println();
sorting(numbers);
System.out.print("Sorted: ");
for(i = 0; i < NUMBERS_SIZE; ++i){
System.out.print(numbers[i] + " ");
}
}

Please clarify me thats wrong in my selection sort code

In this method only one element is getting sorted rest of the elements are are not sorted.
Please help me to find where the actual problem is
private static int[] selectSort(int[] arr) {
int n = arr.length;
for (int i = 0; i < n - 1; i++) {
int min_Ele = i;
for (int j = 1; j < n; j++) {
if (arr[j] <= arr[min_Ele]) {
min_Ele = j;
}
}
if (i != min_Ele) {
int tmp = arr[i];
arr[i] = arr[i = min_Ele];
arr[min_Ele] = tmp;
}
}
return arr;
}
Your mistake is that your inner loop should start from i+1 and not from 1.
public static int[] selectSort(int[] arr) {
int n = arr.length;
for (int i = 0; i < n - 1; i++) {
int min_Ele = i;
for (int j = i+1; j < n; j++) {
if (arr[j] <= arr[min_Ele]) {
min_Ele = j;
}
}
if (i != min_Ele){
//swap
int tmp = arr[i];
arr[i] = arr[i = min_Ele];
arr[min_Ele] = tmp;
}
return arr;
}
private static int[] selectSort(int[] arr) {
int n = arr.length;
for (int i = 0; i < n-1; i++) {
int min_Ele = i;
for (int j = i+1; j < n; j++) {
if (arr[j] <= arr[min_Ele]) {
min_Ele = j;
}
}
if (i != min_Ele) {
int tmp = arr[i];
arr[i] = arr[min_Ele];
arr[min_Ele] = tmp;
}
}
return arr;
}

Categories

Resources