Showing posts with label Bubble Sort. Show all posts
Showing posts with label Bubble Sort. Show all posts

Sunday, May 13, 2018

Find the largest product of any two numbers in a list

Problem statement: Find the largest product of any two numbers in a list
Input - a list of numbers
Output - the largest product of any 2 numbers in the list
e.g. - [1 7 3 4 2 6 5]  => 42
  1. public class ProductOfLargestNum {
  2. public static void main(String[] args) {

  3. int a[] = { 1, 7, 3, 4, 2, 6, 5 };
  4. int temp;
  5. /*
  6. * logic is to sort the list first then get last and last but one
  7. * element and do the product
  8. */
  9.    // bubble sort algorithm
  10. for (int i = 0; i < a.length; i++) {
  11. for (int j = 0; j < a.length - 1; j++) {
  12. if (a[j] > a[j + 1]) {
  13. temp = a[j];
  14. a[j] = a[j + 1];
  15. a[j + 1] = temp;
  16. }
  17. }
  18. }
  19. System.out.println("list after sorting");
  20. for (int i : a) {
  21. System.out.print(i + " ");
  22. }
  23. int last = a[a.length - 1];
  24. int lastButOne = a[a.length - 2];
  25. System.out.println();
  26. System.out.println(last * lastButOne);
  27. }
  28. }
Output:
list after sorting
1 2 3 4 5 6 7 

42

Thursday, April 19, 2018

Write a program to sort numeric array !!

// Method-I:
  1. public class SortIntegerArrayAlgorithm {
  2. public static void main(String[] args) {
  3. int a[] = { 2, 3, 4, 5, 22, 13, 5, 3 };
  4. int temp;
  5. for (int i = 0; i < a.length; i++) {
  6. for (int j = 0; j < a.length - 1; j++) {
  7. if (a[j] > a[j + 1]) {
  8. temp = a[j];
  9. a[j] = a[j + 1];
  10. a[j + 1] = temp;
  11. }
  12. }
  13. }
  14. for (int i : a) {
  15. System.out.print(i + " ");
  16. }
  17. }
  18. }
Output: 2 3 3 4 5 5 13 22
Note: This is also called Bubble sort algorithm.

// Method-II:
  1. public class SortIntArrayAlgorithm {

  2. public static void main(String[] args) {
  3. int a[] = { 1, 43, 4, 43, 33, 2, 2, 5, 5, 5, 5, 33, 777 };
  4. Arrays.sort(a);
  5. for (int i : a) {
  6. System.out.print(i + " ");
  7. }
  8. }
  9. }
Output: 1 2 2 4 5 5 5 5 33 33 43 43 777 
Note: Sorting has been done using pre-defined method not our own algorithm.

Blueprint for self-improvement

To learn faster: Make the process fun To understand yourself : Write To understand the world better : Read To build deeper connection : Lis...