Reputation: 77
I created a Java program that takes the user's choice and creates an int array of that size. Then the array is sorted and displayed and a number is asked to search in the array. I'm trying to use the bubble sort technique, however, the result always turns out to be a descending array rather than an ascending one.
import java.util.*;
class mt {
int i,M=0;
public void main() {
Scanner sc=new Scanner(System.in);
System.out.println("enter the size of array");
int sizeOfArray=sc.nextInt();
int arr[]= new int [sizeOfArray];
int temp;
System.out.println("enter the numbers");
for (i=0; i<sizeOfArray; i++) {
arr[i]=sc.nextInt();
}
System.out.println("the sorted array is below :");
for ( i=0; i<sizeOfArray-1; i++){
for (int j=0; j<sizeOfArray-2; j++) {
if (arr[j]>arr[j+1]) {
temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}
for (i=0; i<sizeOfArray; i++) {
System.out.print(arr[i]+" ");
}
System.out.println();
System.out.println("enter number to search");
int srch=sc.nextInt();
for (i=0; i<sizeOfArray; i++) {
if (arr[i]==srch)
{
System.out.println("found at "+i);
M++;
break;
}
else if (M==0&&i==sizeOfArray-1)
{
System.out.println("number not found");
}
}
}
}
Upvotes: 2
Views: 66
Reputation: 309
Firstly the code mentioned above had lot of silly mistakes which need to be corrected: 1. "String args[]" need to be added in the main() method. 2. For all the for loops where "i" is the variable, it need to be defined as an "int". 3. the variable "M" need to be defined too.
Now when I did a dry run of this code, the result produced was also not proper. Input given was as follows: enter the size of array 5 enter the numbers 12 10 34 2 6 Output received was as below: the sorted array is below : 2 10 12 34 6 enter number to search
Now the output was incorrect. Although it was in ascending order... still the last element would get missed. The twin for loops that are used need to be used in a different way. Please find the code that should be present in that section:
for (int i=0; i<=sizeArr; i++){
for (int j=0; j<sizeArr-1; j++) {
if (arr[j]>arr[j+1]) {
temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}
I hope that this works for you now.
Upvotes: 1
Reputation: 37023
Change your loops and condition as below
for ( i=0; i<arr.length - 1; i++){
for (int j=i+1; j<arr.length; j++) {
if (arr[i]>arr[j]) {
temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
}
So you get resulting array in ascending order. In your case, you are missing elements as you are iterating over from 0 - array.length - 2.
Upvotes: 1