Thursday, April 19, 2018

Write a program to sort a string array !!

// Method-I: (Using our own algorithm)

  1. public class SortStringArrayByOwnAlgorithm {
  2. public static void main(String[] args) {
  3. String s[] = { "Java", "C++", "Python", "ruby", "Perl", "ishaan" };
  4. String temp;
  5. for (int i = 0; i < s.length; i++) {
  6. for (int j = 0; j < s.length-1; j++) {
  7. if (s[j].compareTo(s[j+1]) > 0) {
  8. temp = s[j];
  9. s[j] = s[j+1];
  10. s[j+1] = temp;
  11. }
  12. }
  13. }
  14. for (String str : s) {
  15. System.out.print(str + " ");
  16. }
  17. }
  18. }
Output: C++ Java Perl Python ishaan ruby


// Mehod-II: (Using our own algorithm)
  1. public class SortStringArrayByOwnAlgorithm {
  2. public static void main(String[] args) {
  3. String s[] = { "Java", "C++", "Python", "ruby", "Perl", "ishaan" };
  4. String temp;
  5. for (int i = 0; i < s.length; i++) {
  6. for (int j = i + 1; j < s.length; j++) {
  7. if (s[i].compareTo(s[j]) < 0) {
  8. temp = s[i];
  9. s[i] = s[j];
  10. s[j] = temp;
  11. }
  12. }
  13. }
  14. for (String str : s) {
  15. System.out.print(str + " ");
  16. }
  17. }
  18. }
Output: ruby ishaan Python Perl Java C++


// Mehod-III: (Using pre-defined API)
  1. public class SortStringArrayAlgorithmExe {
  2. public static void main(String[] args) {
  3. String s[] = { "Java", "C++", "Python", "ruby", "Perl", "ishaan" };
  4. Arrays.sort(s);
  5. for (String str : s) {
  6. System.out.print(str + " ");
  7. }
  8. }
  9. }
Output: C++ Java Perl Python ishaan ruby 

No comments:

Post a Comment

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...