ตัวอย่างโค้ด
import java.util.*;
public class Demo {
static void sort_elements(String[] my_str, int n) {
for (int i = 1; i < n; i++) {
String temp = my_str[i];
int j = i - 1;
while (j >= 0 && temp.length() < my_str[j].length()) {
my_str[j + 1] = my_str[j];
j--;
}
my_str[j + 1] = temp;
}
}
public static void main(String args[]) {
String[] my_arr = {"This", "is", "a", "sample"};
int len = my_arr.length;
sort_elements(my_arr, len);
System.out.print("The sorted array is : ");
for (int i = 0; i < len; i++)
System.out.print(my_arr[i] + " ");
}
}
ผลลัพธ์
The sorted array is : a is This sample
คลาส Demo มีฟังก์ชัน sort_elements ใช้ insertion sort เรียงคำในอาร์เรย์ตามความยาวของคำ (length) จากน้อยไปมาก ใน main กำหนดอาร์เรย์ String เรียกฟังก์ชันเรียง แล้วพิมพ์ผลลัพธ์