Reputation:
//the problem I am facing with this is it does not sorts the array correctly //what it does is it misses first number and and starts from second sorting
package exception;
import java.io.*;
public class Program6 {
public static void main(String args[]) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter numbers: ");
int n = Integer.parseInt(br.readLine());
int arr []= new int[n];
for(int i=0; i<n; i++) {
System.out.print("enter int:");
arr[i] = Integer.parseInt(br.readLine());
}
int limit = n-1;
boolean flag = false;
int temp;
for (int i=0; i<limit; i++) {
for(int j =0; j<limit-1; j++) {
if(arr[j]>arr[j+1]) {
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
flag = true;
}
}
if(flag==false) break;
else flag=false;
System.out.println("sorted array: ");
for(i=0; i<n; i++)
System.out.println(arr[i]);
}
}
}
Upvotes: 0
Views: 52
Reputation: 184
package exception;
import java.io.*;
public class Program6 {
public static void main(String args[]) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter numbers: ");
int n = Integer.parseInt(br.readLine());
int arr []= new int[n];
for(int i=0; i<n; i++) {
System.out.print("enter int:");
arr[i] = Integer.parseInt(br.readLine());
}
int limit = n-1;
int temp;
for (int i=0; i<limit; i++) {
boolean flag=false;
for(int j =0; j<limit-i; j++) { //Replace limit-1 with limit-i
if(arr[j]>arr[j+1]) {
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
flag = true;
}
}
if(flag==false) break;
System.out.println("sorted array: ");
for(i=0; i<n; i++)
System.out.println(arr[i]);
}
}
}
Upvotes: 0
Reputation: 19565
There are two main issues in the presented code:
int limit = n - 1
and additionally decreasing the length in the nested loop: for (int j = 0; j < limit - 1; j++)
- thus, the last element of the array is excluded from sorting.j < limit - i
, then for the first iteration the maximal number "bubbles up" to the last element of array at index n - 1
.i
so that after printing i
becomes n
and the outer loop is done after just 1 iteration.Fixed code is:
int limit = n - 1;
for (int i = 0; i < limit; i++) {
boolean flag = false;
for (int j = 0; j < limit - i; j++) { // <<-- Replace limit-1 with limit-i
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
flag = true;
}
}
if(!flag) break;
}
System.out.println("sorted array: ");
for(int i = 0; i < n; i++)
System.out.print(arr[i] + " ");
System.out.println();
Upvotes: 1