How can I get rid of duplicates in this Java code? - java

How can I make this code not have any repeating numbers in it?
All I would like to do is make it so that it doesn't output any duplicates
in this little block.
int[] arr = {5,10,44,2, 44,44,5,10,44,2, 44,44};
int startScan;
int index;
int minindex;
int minValue;
for (startScan=0;startScan<(arr.length-1);startScan++){
minindex=startScan;
minValue =arr[startScan];
for (index=startScan+1; index<arr.length;index++){
if (arr[index]<minValue){
minValue=arr[index];
minindex=index;
}
}
arr[minindex]=arr[startScan];
arr[startScan]=minValue;
}
for(int x=0; x<arr.length;x++)
System.out.println(arr[x]);

Your code sorted the int array in ascending order. It would have been nice if you had mentioned that in your question, and not left it for someone else to spend time figuring out.
Removing the duplicates required some extra code.
Here is the results of a test run.
[2, 5, 10, 44]
Here's the revised version of your code. It's runnable, so you can copy the code and paste it into your IDE.
package com.ggl.testing;
import java.util.Arrays;
public class RemoveDuplicates {
public static void main(String[] args) {
int[] arr = { 5, 10, 44, 2, 44, 44, 5, 10, 44, 2, 44, 44 };
int masterIndex = 0;
for (int startScan = 0; startScan < (arr.length - 1); startScan++) {
int minindex = startScan;
int minValue = arr[startScan];
for (int index = startScan + 1; index < arr.length; index++) {
if (arr[index] < minValue) {
minValue = arr[index];
minindex = index;
}
}
arr[minindex] = arr[startScan];
arr[startScan] = minValue;
if (arr[masterIndex] < minValue) {
arr[++masterIndex] = minValue;
}
}
int[] newarr = Arrays.copyOf(arr, masterIndex + 1);
System.out.println(Arrays.toString(newarr));
}
}

Related

Create array which stores odds from -6 to 38 in java

I'm learning Java and I found an exercise which I can't solve, in the Arrays chapter.
The exercise says:
Write code that creates an array named odds and stores all odd numbers between -6 and 38 into it using a for loop. Make the array's size exactly large enough to store the numbers.
The only solution I could come up with is this:
import java.util.Arrays;
public class exerciseOddsArray {
public static void main(String[]args){
oddsArray();
}
public static void oddsArray(){
int odds = 0;
for (int i = -6; i <= 38; i++){
if (i % 2 == 1){
odds++;
}
}
int[] numbers = new int[odds];
for (int i = 0; i < numbers.length; i ++){
for (int j = -6; j <= 38; j++){
if(j % 2 == 1){
numbers[i] = j;
}
}
}
System.out.println(Arrays.toString(numbers));
}
}
However, the program prints:
[37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37]
And I don't understand why.
You don't need nested FOR loops here. Just create an integer variable i to track your position in the array and increment it when adding each new item. PS... the array should have been called "odds" based on the specs of the assignment. I suggest renaming that variable you were using to count the number of odds to something else (e.g. numberOfOdds)
int[] odds= new int[numberOfOdds];
int i = 0;
for (int j = -6; j <= 38; j++)
{
if(j % 2 == 1)
{
odds[i++] = j;
}
}
for each i you go over all the odd number j could have and assign them to numbers[i]. Instead, you could (should!) use a single loop:
int min = -6;
int max = 38;
int numOdds = (max - min) / 2; // Ok because both min and max are even
int[] odds = new int[numOdds];
int firstOdd = min;
if (min % 2 == 0) {
++firstOdd;
}
int index = 0;
for (int i = firstOdd; i < max; i += 2) {
odds[index++] = i;
}
BTW - I get this is a school exercise, and that you're supposed to use a for loop, but frankly, Java 8's streams would solve this in a much neater fashion:
odds = IntStream.range(-6, 38).filter(i -> i % 2 != 0).toArray();
odds is a single value, you need to keep all the odd numbers you find in a list.
int odds = 0;
You have two for loops when you only need one.
Unrolling the loops, your program is doing the following:
numbers[0] = -6;
numbers[0] = -4;
numbers[0] = -2;
etc...
numbers[0] = 37;
numbers[1] = -6;
numbers[1] = -4;
etc...
Try the below below please
public static ArrayList<Integer> getOddList(int min,int max){
ArrayList<Integer> myList = new ArrayList<>();
for( int i = min ; i <= max ; i++){
if(i % 2 != 0){
myList.add(i);
}
}
return myList;
}
[-5, -3, -1, 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37]
I am assuming here min and max u r providing are in order. Also I have not tested my function. But this is an utility u can take. Please let me know
U created int value and changed it 22 times i guess in first for loop. Then u add for your array the same value for another million times. Try to add your value to an array in first loop:
int[] odds= new int[numberOfOdds];
int i = 0;
for (int j = -6; j <= 38; j++)
{
if(j % 2 == 1)
{
odds[i++] = j;
}
}
Better use list if u don't know length of your set.
Thank you guys for the answers. I changed my method to :
public static void oddsArray(){
int numberOfOdds = 0;
for (int i = -6; i <= 38; i++){
if (i % 2 == 1){
numberOfOdds++;
}
}
int[] odds = new int[numberOfOdds];
int i = 0;
for (int j = -6; j < 39; j++){
if (j % 2 == 1){
odds[i++] = j;
}
}
}
Now it prints only the positive odd numbers.
You can do this without knowing the number of odd numbers in advance.
int[] oddNumbers = IntStream.range(-6, 38)
.filter(i -> i % 2 != 0)
.toArray();
I'm not sure if it's necessary, but you could recreate the array holding the odd numbers each time you come across a new odd number. The method below will work no matter what range you are working with. I know that you can just use an ArrayList, but the question seems to want an array.
public class exerciseOddsArray {
public static void main(String[] args) {
private int[] odds;
private int start = -6;
private int end = 38;
odds = findOdds(start, end);
if (odds== null)
System.out.println("There weren't any odds");
else
System.out.println(Arrays.toString(odds));
}
public static int[] findOdds(int start, int end) {
private int[] arrayOfOdds;
private int[] tempArray;
private int numberOfOdds = 0;
if (start < end)
{
while (start != end)
{
if ((start % 2) == 1)
{
if (arrayOfOdds != null)
{
tempArray = new int[arrayOfOdds.length + 1];
for (int i = 0; i < arrayOfOdds.length; i++)
tempArray[i] = arrayOfOdds[i];
tempArray[arrayOfOdds.length] = start;
arrayOfOdds = tempArray;
} else {
arrayOfOdds = new int[1];
arrayOfOdds[0] = start;
}
}
start++;
}
}
return arrayOfOdds;
}
}
I have answer, this works
int[] odds = new int[22];
for(int i = 0;i<odds.length;i++){
odds[i]=2*i-5;
}
Number of odds is 22, this can be changed, but you must also change the parameters (ie. -6 and 38)
int[] odds = new int [22];
int i = 0;
for (int temp = -6; temp <= 38; temp++)
if (Math.abs(temp % 2) == 1)
{
odds[i++] = temp;
}

Using an array to find the multiples of two ints

Im a programming student and im having alot of trouble with this question:
"complete a static method multiplesOf which takes two int parameters, number and count. The method body must return an int array containing the first count multiples of number. For example,
multiplesOf(5, 4) should return the array { 5, 10, 15, 20 }
multiplesOf(11, 3) should return the array { 11, 22, 33 }
multiplesOf(1, 15) should return the array { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }
You must not use System.out.print or System.out.println in your method."
This is my current code:
public static void main(String[] args) {
multiplesOf(5,4);
}
public static int[] multiplesOf (int number, int count) {
int[] a = new int[count];
a[0]= number;
for(int i = 0; i<count; i++) {
a[i] = (a[i]*count);
}
return a;
}
Ive been trying to figure out why the array "a" still only has the values 0,1,2,3
Try:
public static int[] multiplesOf(int number, int count) {
int[] a = new int[count];
for(int i = 1; i <= count; i++) {
a[i - 1] = number * i;
}
return a;
}
a[0] = number;
for(int i = 1; i<count; i++)
{
a[i] = (i+1)*number;
}
try this
public static int[] multiplesOf (int number, int count)
{
int[] a = new int[count];
a[0] = number;
for(int i = 1; i<count; i++)
{
a[i] = number * (i + 1);
}
return a;
}
output
[5, 10, 15, 20]
public static int[] multiplesOf(int number, int count) {
int[] a = new int[count];
for (int i = 0; i < count; i++) {
a[i] = (number * (i+1));
}
return a;
}
use this
public static int[] multiplesOf (int number, int count) {
int[] a = new int[count];
for(int i = 1; i<=count; i++) {
//a[i-1] beacuse we started iterating array at i=1
a[i-1] = (i*number);
}
return a;
}
multiplesOf(5, 4) returns -> the array { 5, 10, 15, 20 }

Switch Maximum and Minimum values in Two Dimensional Array

I'm trying to switch the minimum and maximum values of the array.
My code:
public static void swap(int[][] a, int i0, int j0, int i1, int j1) {
int temp = a[i0][j0];
a[i0][j0] = a[i1][j1];
a[i1][j1] = temp;
}
public static void main(String args[]){
int max = 0, min = 0, tmpI = 0, tmpJ = 0, tmpI1 = 0, tmpJ1 = 0;
int[][] a = {{10,9,20} , {2,10,10}};
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
if (min > a[i][j]) {
min = a[i][j];
tmpI1 = i; tmpJ1 = j;
}
if (max < a[i][j]) {
max = a[i][j];
tmpI = i; tmpJ = j;
}
}
}
System.out.println(Arrays.deepToString(a));
swap(a,tmpI1,tmpJ1,tmpI,tmpJ);
System.out.println(Arrays.deepToString(a));
}
Output:
[[10, 9, 20], [2, 10, 10]]
[[20, 9, 10], [2, 10, 10]]
It is switching only to the first number for some reason. Any help? I'm new to java.
The issue is with your initial value of min (0). When you say,
if (min > a[i][j]) {
it will never be true (because 0 is less than your numbers). Change the declaration of min to something like
min = Integer.MAX_VALUE
because every int value will be less than that.

Java - Merge Two Arrays without Duplicates (No libraries allowed)

Need assistance with programming issue.
Must be in Java. Cannot use any libraries (Arraylist, etc.).
int[] a = {1, 2, 3, 4, 8, 5, 7, 9, 6, 0}
int[] b = {0, 2, 11, 12, 5, 6, 8}
Have to create an object referencing these two arrays in a method that merges them together, removes duplicates, and sorts them.
Here's my sort so far. Having difficulty combining two arrays and removing duplicates though.
int lastPos;
int index;
int temp;
for(lastPos = a.length - 1; lastPos >= 0; lastPos--) {
for(index = 0; index <= lastPos - 1; index++) {
if(a[index] > a[index+1]) {
temp = a[index];
a[index] = a[index+1];
a[index+1] = temp;
}
}
}
a method that merges them together, removes duplicates, and sorts them.
I suggest you break this down into helper methods (and slightly tweak the order of operations). Step 1, merge the two arrays. Something like,
static int[] mergeArrays(int[] a, int[] b) {
int[] c = new int[a.length + b.length];
for (int i = 0; i < a.length; i++) {
c[i] = a[i];
}
for (int i = 0; i < b.length; i++) {
c[a.length + i] = b[i];
}
return c;
}
Step 2, sort the new array (your existing sort algorithm is fine). Like,
static void sortArray(int[] a) {
for (int lastPos = a.length - 1; lastPos >= 0; lastPos--) {
for (int index = 0; index <= lastPos - 1; index++) {
if (a[index] > a[index + 1]) {
int temp = a[index];
a[index] = a[index + 1];
a[index + 1] = temp;
}
}
}
}
Finally, remove duplicates. Step 3a, count unique values. Assume they're unique, and decrement by counting adjacent (and equal) values. Like,
static int countUniqueValues(int[] c) {
int unique = c.length;
for (int i = 0; i < c.length; i++) {
while (i + 1 < c.length && c[i] == c[i + 1]) {
i++;
unique--;
}
}
return unique;
}
Then step 3b, take the unique count and build your result with the previous methods. Like,
public static int[] mergeDedupSort(int[] a, int[] b) {
int[] c = mergeArrays(a, b);
sortArray(c);
int unique = countUniqueValues(c);
int[] d = new int[unique];
int p = 0;
for (int i = 0; i < c.length; i++) {
d[p++] = c[i];
while (i + 1 < c.length && c[i] == c[i + 1]) {
i++;
}
}
return d;
}
Then you can test it with your arrays like
public static void main(String[] args) {
int[] a = { 1, 2, 3, 4, 8, 5, 7, 9, 6, 0 };
int[] b = { 0, 2, 11, 12, 5, 6, 8 };
int[] c = mergeDedupSort(a, b);
System.out.println(Arrays.toString(c));
}
And I get
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12]
Merge Two Arrays without Duplicates and Sort it (No libraries used).
Using an object.
public class MergeRemoveDupSort {
public int[] mergeRemoveDupSortIt(int[] a, int[] b) {
int [] c = mergeIt(a,b);
int [] d = removeIt(c);
int [] e = sortIt(d);
return e;
}
private int[] mergeIt(int[] a, int[] b) {
int[] c = new int[a.length + b.length];
int k=0;
for (int n : a) c[k++]=n;
for (int n : b) c[k++]=n;
return c;
}
private int[] removeIt(int[] c) {
int len=c.length;
for (int i=0;i<len-1;i++)
for (int j=i+1;j<len;j++)
if (c[i] == c[j]) {
for (int k=j;k<len-1;k++)
c[k]=c[k+1];
--len;
}
int [] r = new int[len];
for (int i=0;i<r.length;i++)
r[i]=c[i];
return r;
}
private int[] sortIt(int[] a) {
for(int index=0; index<a.length-1; index++)
for(int i=index+1; i<a.length; i++)
if(a[index] > a[i]){
int temp = a[index];
a[index] = a[i];
a[i] = temp;
}
return a;
}
public void printIt(int[] a) {
System.out.print("[");
for (int i=0;i<a.length;i++){
System.out.print(a[i]);
if (i!=a.length-1) System.out.print(",");
else System.out.print("]");
}
}
public static void main(String[] args) {
int[] a = {1, 2, 3, 4, 8, 5, 7, 9, 6, 0};
int[] b = {0, 2, 11, 12, 5, 6, 8};
MergeRemoveDupSort array = new MergeRemoveDupSort();
int [] r = array.mergeRemoveDupSortIt(a, b);
array.printIt(r);
}
}
You should use IntStream like this.
int[] a = {1, 2, 3, 4, 8, 5, 7, 9, 6, 0};
int[] b = {0, 2, 11, 12, 5, 6, 8};
int[] merged = IntStream
.concat(IntStream.of(a), IntStream.of(b))
.distinct()
.sorted()
.toArray();
System.out.println(Arrays.toString(merged));
Assuming that array a and array b are sorted, the following code will merge them into a third array merged_array without duplicates :
public static int[] get_merged_array(int[] a, int[] b, int a_size, int b_size)
{
int[] merged_array = new int[a_size + b_size];
int i = 0 , j = 0, x = -1;
for(; i < a_size && j < b_size;)
{
if(a[i] <= b[j])
{
merged_array[++x] = a[i];
++i;
}
else
{
if(merged_array[x] != b[j])
{
merged_array[++x] = b[j]; // avoid duplicates
}
++j;
}
}
--i; --j;
while(++i < a_size)
{
merged_array[++x] = a[i];
}
while(++j < b_size)
{
merged_array[++x] = b[j];
}
return merged_array;
}
Hope this may help, all the best :)
try{
int[] a = {1, 2, 3, 4, 8, 5, 7, 9, 6, 0};
int[] b = {0, 2, 11, 12, 5, 6, 8};
int[] c = new int[a.length+b.length];
int[] final = new int[a.length+b.length];
int i = 0;
for(int j : final){
final[i++] = -1;
}
i = 0;
for(int j : a){
c[i++] = j;
}
for(int j : b){
c[i++] = j;
}
boolean check = false;
for(int j = 0,k = 0; j < c.length; j++){
for(int l : fin){
if( l == c[j] )
check = true;
}
if(!check){
final[k++] = c[j];
} else check = false;
}
} catch(Exception ex){
ex.printStackTrace();
}
I prefer you to use Hashset for this cause it never allow duplicates
and there is another method in java 8 for arraylist to remove duplicates
after copying all elements to c follow this code
List<Integer> d = array.asList(c);
List<Integer> final = d.Stream().distinct().collect(Collectors.toList());
final.forEach(System.out::println());
This code is lot much better than previous one and you can again transform final to array like this
int array[] = new int[final.size()];
for(int j =0;j<final.size();j++){
array[j] = final.get(j);
}
Hope my work will be helpful .
Let me restate your question.
You want a program that takes two arbitrary arrays, merges them removing any duplicates, and sorts the result.
First of all, if you have access to any data structure, there are much better ways of doing this. Ideally, you would use something like a TreeSet.
However, assuming all you have access to is arrays, your options are much more limited. I'm going to go ahead and assume that each of the two arrays initially has no duplicates.
Let's assume the first array is of length m and the second array is of length n.
int[] array1; // length m
int[] array2; // length n
First, let's sort both arrays.
Arrays.sort(array1);
Arrays.sort(array2);
This assumes you have access to the Arrays class which is part of the standard Java Collections Framework. If not, any reasonable merge implementation (like MergeSort) will do the trick.
The sorts will take O(n log n + m log m) with most good sort implementations.
Next, let's merge the two sorted arrays. First, we need to allocate a new array big enough to hold all the elements.
int[] array3 = new int[size];
Now, we will need to insert the elements of array1 and array2 in order, taking care not to insert any duplicates.
int index=0, next=0, i=0, j=0;
int last = Integer.MAX_INT;
while(i < m || j < n) {
if(i == m)
next = array2[j++];
else if(j == n)
next = array1[i++];
else if(array1[i] <= array2[j])
next = array1[i++];
else
next = array2[j++];
if(last == next)
continue;
array3[index++] = next;
}
Now, you have your array. Just one problem - it could have invalid elements at the end. One last copy should take care of it...
int[] result = Arrays.copyOf(array3, index + 1);
The inserts and the final copy will take O(n + m), so the overall efficiency of the algorithm should be O(n log n + m log n).

Java : Sort integer array without using Arrays.sort()

This is the instruction in one of the exercises in our Java class. Before anything else, I would like to say that I 'do my homework' and I'm not just being lazy asking someone on Stack Overflow to answer this for me. This specific item has been my problem out of all the other exercises because I've been struggling to find the 'perfect algorithm' for this.
Write JAVA program that will input 10 integer values and display either in ascending or descending order. Note: Arrays.sort() is not allowed.
This is the code I have come up with, it works but it has one obvious flaw. If I enter the same value twice or more, for example:
5, 5, 5, 4, 6, 7, 3, 2, 8, 10
Only one of the three 5s entered would be counted and included in the output. The output I get (for the ascending order) is:
2 3 4 5 0 0 6 7 8 10.
import java.util.Scanner;
public class Exer3AscDesc
{
public static void main(String args[])
{
Scanner scan = new Scanner(System.in);
int tenNums[]=new int[10], orderedNums[]=new int[10];
int greater;
String choice;
//get input
System.out.println("Enter 10 integers : ");
for (int i=0;i<tenNums.length;i++)
{
System.out.print(i+1+"=> ");
tenNums[i] = scan.nextInt();
}
System.out.println();
//imperfect number ordering algorithm
for(int indexL=0;indexL<tenNums.length;indexL++)
{
greater=0;
for(int indexR=0;indexR<tenNums.length;indexR++)
{
if(tenNums[indexL]>tenNums[indexR])
{
greater++;
}
}
orderedNums[greater]=tenNums[indexL];
}
//ask if ascending or descending
System.out.print("Display order :\nA - Ascending\nD - Descending\nEnter your choice : ");
choice = scan.next();
//output the numbers based on choice
if(choice.equalsIgnoreCase("a"))
{
for(greater=0;greater<orderedNums.length;greater++)
{
System.out.print(orderedNums[greater]+" ");
}
}
else if(choice.equalsIgnoreCase("d"))
{
for(greater=9;greater>-1;greater--)
{
System.out.print(orderedNums[greater]+" ");
}
}
}
}
Simple sorting algorithm Bubble sort:
public static void main(String[] args) {
int[] arr = new int[] { 6, 8, 7, 4, 312, 78, 54, 9, 12, 100, 89, 74 };
for (int i = 0; i < arr.length; i++) {
for (int j = i + 1; j < arr.length; j++) {
int tmp = 0;
if (arr[i] > arr[j]) {
tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
}
}
}
You can find so many different sorting algorithms in internet, but if you want to fix your own solution you can do following changes in your code:
Instead of:
orderedNums[greater]=tenNums[indexL];
you need to do this:
while (orderedNums[greater] == tenNums[indexL]) {
greater++;
}
orderedNums[greater] = tenNums[indexL];
This code basically checks if that particular index is occupied by a similar number, then it will try to find next free index.
Note: Since the default value in your sorted array elements is 0, you need to make sure 0 is not in your list. otherwise you need
to initiate your sorted array with an especial number that you sure is
not in your list e.g: Integer.MAX_VALUE
Simple way :
int a[]={6,2,5,1};
System.out.println(Arrays.toString(a));
int temp;
for(int i=0;i<a.length-1;i++){
for(int j=0;j<a.length-1;j++){
if(a[j] > a[j+1]){ // use < for Descending order
temp = a[j+1];
a[j+1] = a[j];
a[j]=temp;
}
}
}
System.out.println(Arrays.toString(a));
Output:
[6, 2, 5, 1]
[1, 2, 5, 6]
Here is one simple solution
public static void main(String[] args) {
//Without using Arrays.sort function
int i;
int nos[] = {12,9,-4,-1,3,10,34,12,11};
System.out.print("Values before sorting: \n");
for(i = 0; i < nos.length; i++)
System.out.println( nos[i]+" ");
sort(nos, nos.length);
System.out.print("Values after sorting: \n");
for(i = 0; i <nos.length; i++){
System.out.println(nos[i]+" ");
}
}
private static void sort(int nos[], int n) {
for (int i = 1; i < n; i++){
int j = i;
int B = nos[i];
while ((j > 0) && (nos[j-1] > B)){
nos[j] = nos[j-1];
j--;
}
nos[j] = B;
}
}
And the output is:
Values before sorting:
12
9
-4
-1
3
10
34
12
11
Values after sorting:
-4
-1
3
9
10
11
12
12
34
I would recommend looking at Selection sort or Insertion sort if you aren't too worried about performance. Maybe that will give you some ideas.
int x[] = { 10, 30, 15, 69, 52, 89, 5 };
int max, temp = 0, index = 0;
for (int i = 0; i < x.length; i++) {
int counter = 0;
max = x[i];
for (int j = i + 1; j < x.length; j++) {
if (x[j] > max) {
max = x[j];
index = j;
counter++;
}
}
if (counter > 0) {
temp = x[index];
x[index] = x[i];
x[i] = temp;
}
}
for (int i = 0; i < x.length; i++) {
System.out.println(x[i]);
}
Bubble sort can be used here:
//Time complexity: O(n^2)
public static int[] bubbleSort(final int[] arr) {
if (arr == null || arr.length <= 1) {
return arr;
}
for (int i = 0; i < arr.length; i++) {
for (int j = 1; j < arr.length - i; j++) {
if (arr[j - 1] > arr[j]) {
arr[j] = arr[j] + arr[j - 1];
arr[j - 1] = arr[j] - arr[j - 1];
arr[j] = arr[j] - arr[j - 1];
}
}
}
return arr;
}
Array Sorting without using built in functions in java ......just make new File unsing this name -> (ArraySorting.java) ..... Run the Project and Enjoy it !!!!!
import java.io.*;
import java.util.Arrays;
import java.util.Scanner;
public class ArraySorting
{
public static void main(String args[])
{
int temp=0;
Scanner user_input=new Scanner(System.in);
System.out.println("enter Size of Array...");
int Size=user_input.nextInt();
int[] a=new int[Size];
System.out.println("Enter element Of an Array...");
for(int j=0;j<Size;j++)
{
a[j]=user_input.nextInt();
}
for(int index=0;index<a.length;index++)
{
for(int j=index+1;j<a.length;j++)
{
if(a[index] > a[j] )
{
temp = a[index];
a[index] = a[j];
a[j] = temp;
}
}
}
System.out.print("Output is:- ");
for(int i=0;i<a.length;i++)
{
System.out.println(a[i]);
}
}
}
int[] arr = {111, 111, 110, 101, 101, 102, 115, 112};
/* for ascending order */
System.out.println(Arrays.toString(getSortedArray(arr)));
/*for descending order */
System.out.println(Arrays.toString(getSortedArray(arr)));
private int[] getSortedArray(int[] k){
int localIndex =0;
for(int l=1;l<k.length;l++){
if(l>1){
localIndex = l;
while(true){
k = swapelement(k,l);
if(l-- == 1)
break;
}
l = localIndex;
}else
k = swapelement(k,l);
}
return k;
}
private int[] swapelement(int[] ar,int in){
int temp =0;
if(ar[in]<ar[in-1]){
temp = ar[in];
ar[in]=ar[in-1];
ar[in-1] = temp;
}
return ar;
}
private int[] getDescOrder(int[] byt){
int s =-1;
for(int i = byt.length-1;i>=0;--i){
int k = i-1;
while(k >= 0){
if(byt[i]>byt[k]){
s = byt[k];
byt[k] = byt[i];
byt[i] = s;
}
k--;
}
}
return byt;
}
output:-
ascending order:-
101, 101, 102, 110, 111, 111, 112, 115
descending order:-
115, 112, 111, 111, 110, 102, 101, 101
class Sort
{
public static void main(String[] args)
{
System.out.println("Enter the range");
java.util.Scanner sc=new java.util.Scanner(System.in);
int n=sc.nextInt();
int arr[]=new int[n];
System.out.println("Enter the array values");
for(int i=0;i<=n-1;i++)
{
arr[i]=sc.nextInt();
}
System.out.println("Before sorting array values are");
for(int i=0;i<=n-1;i++)
{
System.out.println(arr[i]);
}
System.out.println();
for(int pass=1;pass<=n;pass++)
{
for(int i=0;i<=n-1;i++)
{
if(i==n-1)
{
break;
}
int temp;
if(arr[i]>arr[i+1])
{
temp=arr[i];
arr[i]=arr[i+1];
arr[i+1]=temp;
}
}
}
System.out.println("After sorting array values are");
for(int i=0;i<=n-1;i++)
{
System.out.println(arr[i]);
}
}
}
here is the Sorting Simple Example try it
public class SortingSimpleExample {
public static void main(String[] args) {
int[] a={10,20,1,5,4,20,6,4,2,5,4,6,8,-5,-1};
a=sort(a);
for(int i:a)
System.out.println(i);
}
public static int[] sort(int[] a){
for(int i=0;i<a.length;i++){
for(int j=0;j<a.length;j++){
int temp=0;
if(a[i]<a[j]){
temp=a[j];
a[j]=a[i];
a[i]=temp;
}
}
}
return a;
}
}
This will surely help you.
int n[] = {4,6,9,1,7};
for(int i=n.length;i>=0;i--){
for(int j=0;j<n.length-1;j++){
if(n[j] > n[j+1]){
swapNumbers(j,j+1,n);
}
}
}
printNumbers(n);
}
private static void swapNumbers(int i, int j, int[] array) {
int temp;
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
private static void printNumbers(int[] input) {
for (int i = 0; i < input.length; i++) {
System.out.print(input[i] + ", ");
}
System.out.println("\n");
}

Categories