Day 10:-
Problem Statement:-Sorting: Bubble Sort
The problem is an implementation of bubble sort,it was very easy.
did very silly mistake,need to be concious.
import java.util.Scanner;
/**
* @author vikram.shanbogar@gmail.com
* on 8/3/2017.
*/
public class Bsort {
static int swaps = 0;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
long a[] = new long[n];
for (int a_i = 0; a_i < n; a_i++) {
a[a_i] = in.nextInt();
}
sort(a);
printOutputs(a);
}
private static void printOutputs(long[] a) {
System.out.printf("Array is sorted in %d swaps.\n", swaps);
if (a.length > 0) {
System.out.printf("First Element: %d\n", a[0]);
System.out.printf("Last Element: %d", a[a.length - 1]);
}
}
private static void sort(long[] a) {
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a.length-1; j++) {
if (a[j] > a[j+1]) {
exch(a, j, j+1);
swaps++;
}
}
}
}
private static void exch(long[] pq, int i, int j) {
long swap = pq[i];
pq[i] = pq[j];
pq[j] = swap;
}
}
Problem Statement:-Sorting: Bubble Sort
The problem is an implementation of bubble sort,it was very easy.
did very silly mistake,need to be concious.
import java.util.Scanner;
/**
* @author vikram.shanbogar@gmail.com
* on 8/3/2017.
*/
public class Bsort {
static int swaps = 0;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
long a[] = new long[n];
for (int a_i = 0; a_i < n; a_i++) {
a[a_i] = in.nextInt();
}
sort(a);
printOutputs(a);
}
private static void printOutputs(long[] a) {
System.out.printf("Array is sorted in %d swaps.\n", swaps);
if (a.length > 0) {
System.out.printf("First Element: %d\n", a[0]);
System.out.printf("Last Element: %d", a[a.length - 1]);
}
}
private static void sort(long[] a) {
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a.length-1; j++) {
if (a[j] > a[j+1]) {
exch(a, j, j+1);
swaps++;
}
}
}
}
private static void exch(long[] pq, int i, int j) {
long swap = pq[i];
pq[i] = pq[j];
pq[j] = swap;
}
}
No comments:
Post a Comment