Algorithm na haɗama (Greedy Algorithm) a cikin Java: An bayyana shi da Misalai

Algorithm na Greedy wata dabara ce ta ingantawa a cikin Java shirye-shirye da ke nuna zabar mafi kyawun mafita a kowane mataki ba tare da sake dubawa ko la'akari da gaba ba. Maimakon yin la'akari da dukan sararin jihar, wannan algorithm yana zaɓar mafi kyawun zaɓi na yanzu kuma yana fatan wannan zai haifar da mafita mafi kyau a duniya.

Yadda Algorithm na Gari ke Aiki

  1. Mataki 1: Fara daga yanayin farko.

  2. Mataki na 2: A kowane mataki, algorithm yana zaɓar mafi kyawun zaɓi tsakanin zaɓuɓɓukan da ake da su bisa aikin kimantawa.

  3. Mataki 3: Algorithm yana motsawa zuwa sabuwar jiha ta zaɓar mafi kyawun zaɓi.

  4. Mataki na 4: Tsarin yana ci gaba har sai an cika yanayin ƙarewa ko kuma babu ƙarin zaɓuɓɓuka da za a zaɓa daga.

  5. Mataki 5: Mayar da mafita da aka samo.

Fa'idodi da Rashin Amfanin Algorithm Mai Zama

Amfani:

  • Sauƙi: Mai sauƙin fahimta da aiwatarwa.
  • Inganci: Sau da yawa yana buƙatar ƙarancin lokacin ƙididdigewa da ƙwaƙwalwar ajiya idan aka kwatanta da wasu ingantaccen algorithms.
  • Madaidaici don matsalolin da ba a iya gani ba: Ya dace da matsalolin inda la'akari da duk yuwuwar ya yi yawa.

Rashin hasara:

  • Babu mafi kyawun garanti na duniya: Algorithm na iya tsayawa a mafi kyawun bayani na gida ba tare da gano mafi kyawun duniya ba.
  • Rashin hangen nesa: Algorithm sau da yawa baya la'akari da sakamakon yanke shawara da suka gabata.

Misali da Bayani

Misali gama gari na Algorithm na Greedy shine nemo matsalar "Kth Mafi Girman Element". Bari mu ga yadda wannan algorithm ke aiki:

import java.util.Arrays;  
  
public class GreedyAlgorithmExample {  
    static int findKthLargest(int[] nums, int k) {  
        Arrays.sort(nums); // Sort the array  
        return nums[nums.length- k]; // Return the kth largest element  
    }  
  
    public static void main(String[] args) {  
        int[] nums = {3, 1, 2, 4, 5};  
        int k = 2;  
        int result = findKthLargest(nums, k);  
        System.out.println("The " + k + "th largest element is: " + result);  
    }  
}  

A cikin misalin da ke sama, muna amfani da Algorithm na Greedy don nemo kashi na biyu mafi girma a cikin tsararrun lamba. Wannan algorithm din kawai yana tsara tsararru kuma ya dawo da mafi girman kashi kth. Ko da yake ba a ba da tabbacin zama mafi kyau a duniya ba, yana da ingantacciyar mafita ga wannan matsalar.