Blog

  • ProgressArcView implementation for Android

    ProgressArcView implementation for Android

    Would you like the same progress View?

    Here is source code for simple viewsion without customisation from XML.

    package com.hrupin.samples.roundanimation;
    
    import android.content.Context;
    import android.content.res.Resources;
    import android.graphics.Canvas;
    import android.graphics.Color;
    import android.graphics.Paint;
    import android.graphics.RectF;
    import android.os.Bundle;
    import android.os.Parcelable;
    import android.util.AttributeSet;
    import android.view.View;
    
    /**
     * Created by Igor Khrupin www.hrupin.com on 03-05-2017.
     */
    public class ProgressArcView extends View {
        private Paint finishedPaint;
        private Paint unfinishedPaint;
        private Paint innerCirclePaint;
    
        private RectF finishedOuterRect = new RectF();
        private RectF unfinishedOuterRect = new RectF();
        private float progress = 0;
        private int max = 1000;
        private int finishedStrokeColor = Color.parseColor("#ff0000");
        private int unfinishedStrokeColor = Color.parseColor("#4cff0000");
        private int startingDegree = -90;
        private float strokeWidth = dp2px(getResources(), 14.5f);
        private int innerBackgroundColor = Color.parseColor("#ffffff");
    
        private int minSize = (int) dp2px(getResources(), 270);
    
    
        private static final String INSTANCE_STATE = "saved_instance";
        private static final String INSTANCE_MAX = "max";
        private static final String INSTANCE_PROGRESS = "progress";
        private static final String INSTANCE_STARTING_DEGREE = "starting_degree";
    
        public ProgressArcView(Context context) {
            this(context, null);
        }
    
        public ProgressArcView(Context context, AttributeSet attrs) {
            this(context, attrs, 0);
        }
    
        public ProgressArcView(Context context, AttributeSet attrs, int defStyleAttr) {
            super(context, attrs, defStyleAttr);
            initPainters();
        }
    
        protected void initPainters() {
            finishedPaint = new Paint();
            finishedPaint.setAntiAlias(true);
            finishedPaint.setColor(finishedStrokeColor);
            finishedPaint.setStyle(Paint.Style.STROKE);
            finishedPaint.setStrokeWidth(strokeWidth);
    
            unfinishedPaint = new Paint();
            unfinishedPaint.setAntiAlias(true);
            unfinishedPaint.setColor(unfinishedStrokeColor);
            unfinishedPaint.setStyle(Paint.Style.STROKE);
            unfinishedPaint.setStrokeWidth(strokeWidth);
    
            innerCirclePaint = new Paint();
            innerCirclePaint.setAntiAlias(true);
            innerCirclePaint.setColor(innerBackgroundColor);
        }
    
        @Override
        public void invalidate() {
            initPainters();
            super.invalidate();
        }
    
        private float getProgressAngle() {
            return getProgress() / (float) max * 360f;
        }
    
        public float getProgress() {
            return progress;
        }
    
        public void setProgress(float progress) {
            this.progress = progress;
            if (this.progress > getMax()) {
                this.progress %= getMax();
            }
            invalidate();
        }
    
        public int getMax() {
            return max;
        }
    
        public void setMax(int max) {
            if (max > 0) {
                this.max = max;
                invalidate();
            }
        }
    
        public int getStartingDegree() {
            return startingDegree;
        }
    
        public void setStartingDegree(int startingDegree) {
            this.startingDegree = startingDegree;
            this.invalidate();
        }
    
        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            setMeasuredDimension(measure(widthMeasureSpec), measure(heightMeasureSpec));
        }
    
        private int measure(int measureSpec) {
            int result;
            int mode = MeasureSpec.getMode(measureSpec);
            int size = MeasureSpec.getSize(measureSpec);
            if (mode == MeasureSpec.EXACTLY) {
                result = size;
            } else {
                result = minSize;
                if (mode == MeasureSpec.AT_MOST) {
                    result = Math.min(result, size);
                }
            }
            return result;
        }
    
        @Override
        protected void onDraw(Canvas canvas) {
            super.onDraw(canvas);
            float delta = strokeWidth / 2f;
            finishedOuterRect.set(delta, delta, getWidth() - delta, getHeight() - delta);
    
            unfinishedOuterRect.set(delta, delta, getWidth() - delta, getHeight() - delta);
    
            float innerCircleRadius = getWidth() / 2f - strokeWidth;
            canvas.drawArc(unfinishedOuterRect, getStartingDegree() + getProgressAngle(), 360 - getProgressAngle(), false, unfinishedPaint);
            canvas.drawArc(finishedOuterRect, getStartingDegree(), getProgressAngle(), false, finishedPaint);
            canvas.drawCircle(getWidth() / 2.0f, getHeight() / 2.0f, innerCircleRadius, innerCirclePaint);
        }
    
        @Override
        protected Parcelable onSaveInstanceState() {
            final Bundle bundle = new Bundle();
            bundle.putParcelable(INSTANCE_STATE, super.onSaveInstanceState());
            bundle.putInt(INSTANCE_MAX, getMax());
            bundle.putInt(INSTANCE_STARTING_DEGREE, getStartingDegree());
            bundle.putFloat(INSTANCE_PROGRESS, getProgress());
            return bundle;
        }
    
        @Override
        protected void onRestoreInstanceState(Parcelable state) {
            if (state instanceof Bundle) {
                final Bundle bundle = (Bundle) state;
                initPainters();
                setMax(bundle.getInt(INSTANCE_MAX));
                setStartingDegree(bundle.getInt(INSTANCE_STARTING_DEGREE));
                setProgress(bundle.getFloat(INSTANCE_PROGRESS));
                super.onRestoreInstanceState(bundle.getParcelable(INSTANCE_STATE));
                return;
            }
            super.onRestoreInstanceState(state);
        }
    
        public static float dp2px(Resources resources, float dp) {
            final float scale = resources.getDisplayMetrics().density;
            return  dp * scale + 0.5f;
        }
    }

    And here is ProgressArcView usage.
    I’ve implemented delay for click action using this view.

    Case:
    Click action will activated it user hold round button during 10 seconds.

    package com.hrupin.samples.roundanimation;
    
    import android.animation.Animator;
    import android.animation.ValueAnimator;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.view.MotionEvent;
    import android.view.View;
    import android.view.animation.LinearInterpolator;
    
    public class MainActivity extends AppCompatActivity implements View.OnTouchListener {
    
        private ProgressArcView progressArcView;
        private ValueAnimator progressAnim;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            progressArcView = (ProgressArcView)findViewById(R.id.progressArcView);
            progressArcView.setProgress(0);
            progressArcView.setOnTouchListener(this);
        }
    
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if(event.getAction() == MotionEvent.ACTION_DOWN){
                startProgress();
            }else if(event.getAction() == MotionEvent.ACTION_UP){
                if(progressAnim != null){
                    progressAnim.end();
                }
                progressAnim = null;
                if(progressArcView != null){
                    progressArcView.setProgress(0);
                }
            }
            return true;
        }
    
        private void startProgress() {
            if(progressAnim == null) {
                progressAnim = ValueAnimator.ofInt(0, progressArcView.getMax());
                progressAnim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                    public void onAnimationUpdate(ValueAnimator animation) {
                        Integer value = (Integer) animation.getAnimatedValue();
                        if(progressArcView != null){
                            progressArcView.setProgress(value);
                        }
                    }
                });
    
                progressAnim.addListener(new Animator.AnimatorListener() {
                    @Override
                    public void onAnimationStart(Animator animation) {
    
                    }
    
                    @Override
                    public void onAnimationEnd(Animator animation) {
                        if(progressArcView != null){
                            progressArcView.setProgress(0);
                        }
                        progressAnim = null;
                    }
    
                    @Override
                    public void onAnimationCancel(Animator animation) {
    
                    }
    
                    @Override
                    public void onAnimationRepeat(Animator animation) {
    
                    }
                });
    
                progressAnim.setDuration(10000);
                progressAnim.setInterpolator(new LinearInterpolator());
                progressAnim.start();
            }
        }
    }

    Source code:

    Download it from github
  • Android & Continuous Integration & HockeyApp

    Android & Continuous Integration & HockeyApp

    Hey!

    Here is the case. We need build Android application, test it using Continuous Integration. After that we need upload APK to HockeyApp.

    The first part is well known.

    So, how to upload APK to HockeyApp using command line?

    I’ll refer you to HockeyApp API.

    To make any interaction with HockeyApp we should have Token.

    Here is link for obtaining HockeyApp token: https://rink.hockeyapp.net/manage/auth_tokens

    After that we able create script for sending APK like this:

    curl \
    -F "status=2" \
    -F "notify=1" \
    -F "notes=NOTES HERE" \
    -F "notes_type=0" \
    -F "ipa=@build.apk" \
    -H "X-HockeyAppToken:TOKEN_HERE" \
    https://rink.hockeyapp.net/api/2/apps/upload

     

  • Calendar DayView for Android

    Calendar DayView for Android

    I had to create logic which should arrange events properly on DayView timeline.
    I’ve researched many solutions in the internet and here is solution which can be easy implemented in Android.
    I’ve implemented this task visually like Google Calendar. Like this.

    Please have a look my solution.

    To draw the DayView we need do the next steps:

    1. Sort events by start time and end time.
    2. Find events which have shared time. Even that just 1 minute. This group of events called Clique.
    3. Find cliques which have shared events. This group of cliques called Clusters.

    Cliques and clusters you can see in the attached image.

    Cliques – blue ovals, Clusters – red ovals.

    After that we can start draw the clusters.

    1. Y coordinate for event calculated from start and end event time.
    2. X coordinate for event calculated based on event width and position in cluster.
    3. WIDTH for event = SCREEN_WIDTH / MAX_CLIQUE_SIZE_IN_CLUSTER.

    Example:
    Cluster contains 5 events arranged by start and end time.
    Max clique size = 3;
    Event Width = screen_width / 3;

    Event1:
    X = 0 * width = 0;

    Event2:
    X = 1 * width;

    Event1:
    X = 2 * width;

    Event1:
    X = 0 * width = 0;

    Event1:
    X = 1 * width;

    That’s all.

    The source code on github.

    Please let me know what you think about this solution in comments

    Download it from github

     

  • Example usage of GeofencingApi in Android

    Example usage of GeofencingApi in Android

    GeofencingApi is great feature for making notifications when user enter to specific place on map and also exit from specific place.

    I’ve updated official GeofencingApi tutorial to make it more visual.

    Here application which able register geofence just after map click. Use it for register your place and test how it works. This app have nice overlays which show whole geofence area (Red circle).

    Here is YouTube with app in action

    And link to github

    Download it from github
  • How to keep background activities in Xiaomi Redmi Note 3 with MIUI 8.1.3.0

    How to keep background activities in Xiaomi Redmi Note 3 with MIUI 8.1.3.0

    If you see this post then you probably have problem with running Android Service or other background activity in Xiaomi Redmi Note 3 phone.

    MIUI ROM usually kill background activity after 5-10 minutes user inactivity.

    So, how to make applications with location based or other services works with MIUI.

    For now I’ve got solution which can be done by end user.

    1. End user should go to Settings –> Battery & performance –> Manage apps battery usage –> Choose apps.
    2. Click on application.
    3. Choose “No restriction”
    4. And if your application work with background location the also choose “Allow” for BACKGROUND LOCATION.

    Below short video with these steps

  • How to Dynamically or Programmatically Add Menu Items for an Android Activity

    How to Dynamically or Programmatically Add Menu Items for an Android Activity

    2017-03-04-17-25-56

    Sometimes you don’t need huge menu. And int is’t super important create XML file for it.

    You can just create your menu from code. It is very simple.

    You need override `

    public boolean onPrepareOptionsMenu(Menu menu)

    ` method. Let’s see the example below:

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        menu.clear();
        menu.add(0, MENU_EDIT, Menu.NONE, getString(R.string.menu_action_edit)).setIcon(R.drawable.ic_action_edit).setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
        menu.add(0, MENU_DELETE, Menu.NONE, getString(R.string.menu_action_delete)).setIcon(R.drawable.ic_action_delete).setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
        return super.onPrepareOptionsMenu(menu);
    }

    Here is you have created two menu items “Edit” and “Delete”. This menu items has showAsAction `

    MenuItem.SHOW_AS_ACTION_ALWAYS

    `. You can change it for your requirements. Also you can group menu items. For example my menu items in group with id = 0.

    Also you can handle menu click actions. It is pretty same to XML menus. Let’s see:

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case MENU_EDIT:
                Toast.makeText(this, "Edit menu item clicked", Toast.LENGTH_SHORT).show();
                break;
            case MENU_DELETE:
                Toast.makeText(this, "Delete menu item clicked", Toast.LENGTH_SHORT).show();
                break;
        }
        return false;
    }

    As you can see it is very simple. You don’t need addition files in your project for just two menus. Use this approach.

    Hope it help you.

    Also here is link to github project.

    Download it from github
  • Launch Battery Historian 2.1 on Mac

    Launch Battery Historian 2.1 on Mac

    Android have great tool for tracking battery drain. It is Battery Historian.

    Here is simple steps how to get it on your Mac:

    1. Install Docker
    2. Run the next commands in Terminal
      docker pull gcr.io/android-battery-historian:2.1
      docker -- run -p 9999:9999 gcr.io/android-battery-historian:2.1 --port 9999
    3. Open your http://localhost:9999

    You will have Battery Historian ready for use:

    screenshot-2016-12-06-13-26-09

  • How to prevent screen capturing in Android

    How to prevent screen capturing in Android

    Prevent screen capturing is way for saving your content.

    Android SDK have special flag for it.
    https://developer.android.com/reference/android/view/WindowManager.LayoutParams.html#FLAG_SECURE

    Just declare it in your Activity like this:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
        .....
    }

    And user will see next message when try make screenshot:

    2016-11-25-11-02-43

  • QuickSort (qsort) Algorithm

    QuickSort (qsort) Algorithm

    Overview

    The quicksort algorithm was discovered by Tony Hoare in 1959.

    This algorithm is considered one of the fastest sorting algorithms and shows the best results in most cases.

    Here is the algorithm visualization. Below I will describe how it works.

    The algorithm works on the “divide and conquer” principle.

    Worst case

    asymptotic complexity O(n^2)

    The answer depends on strategy for choosing pivot. In early versions of Quick Sort where leftmost (or rightmost) element is chosen as pivot, the worst occurs in following cases.

    1. Array is already sorted in same order.
    2. Array is already sorted in reverse order.
    3. All elements are same (special case of case 1 and 2)

    It can be fixed by choosing random pivot position

    Task

    Let’s see how the algorithm works on the example of a simple array of 12 numbers.

    [10, 5, 7, 4, 1, 2, 5, 7, 9, 8, 3, 6]

    Below I will describe the steps that will show how this algorithm works.

    Step 1.

    Select “Pivot”. This is the element that will split the array into two parts in the future. On the left side of the pivot, there will be elements that are less than the pivot, and on the right, more or equal. There are many methods for choosing a pivot, and the speed at which the array will be sorted depends on the choice of the pivot. One of the methods for selecting a pivot is to select the last element of the array. Another method is selecting random element, in this case the time complexity always will be O(n log n).

    We also need to create a variable “i”, which will point to the first element in the array, which is less than the pivot and at the same time is closest to it. We also need the index of the current element “j”

    In our case,

    • pivot = 6 (value of the last element in the array),
    • i = 0,
    • j = 0

    Step 2.

    Compare the array element with index j with the pivot. 10 > 6. Array elements do not need to be moved.
    Change the index “j”.
    j = j + 1 = 1

    Step 3.

    Compare the array element with index j with the pivot. 5 < 6. Swap the elements with indices i and j. Now the array looks like this
    [10, 5, 7, 4, 1, 2, 5, 7, 9, 8, 3, 6] –> [5, 10, 7, 4, 1, 2, 5, 7, 9, 8, 3, 6]
    Change the indexes
    i = i + 1 = 1
    j = j + 1 = 2

    Step 4.

    Compare the array element with index j with the pivot. 7 > 6. Array elements do not need to be moved.
    Change the index “j”.
    j = j + 1 = 3

    Step 5.

    Compare the array element with index j with the pivot. 4 < 6. Swap the elements with indices i and j. Now the array looks like this
    [5, 10, 7, 4, 1, 2, 5, 7, 9, 8, 3, 6] –> [5, 4, 7, 10, 1, 2, 5, 7, 9, 8, 3, 6]
    Change the indexes
    i = i + 1 = 2
    j = j + 1 = 4

    Step 6.

    Compare the array element with index j with the pivot. 1 < 6. Swap the elements with indices i and j. Now the array looks like this
    [5, 4, 7, 10, 1, 2, 5, 7, 9, 8, 3, 6] –> [5, 4, 1, 10, 7, 2, 5, 7, 9, 8, 3, 6]
    Change the indexes
    i = i + 1 = 3
    j = j + 1 = 5

    Step 7.

    Compare the array element with index j with the pivot. 2 < 6. Swap the elements with indices i and j. Now the array looks like this
    [5, 4, 1, 10, 7, 2, 5, 7, 9, 8, 3, 6] –> [5, 4, 1, 2, 7, 10, 5, 7, 9, 8, 3, 6]
    Change the indexes
    i = i + 1 = 4
    j = j + 1 = 6

    Step 8.

    Compare the array element with index j with the pivot. 5 < 6. Swap the elements with indices i and j. Now the array looks like this
    [5, 4, 1, 2, 7, 10, 5, 7, 9, 8, 3, 6] –> [5, 4, 1, 2, 5, 10, 7, 7, 9, 8, 3, 6]
    Change the indexes
    i = i + 1 = 5
    j = j + 1 = 7

    Step 9.

    Compare the array element with index j with the pivot. 7 > 6. Array elements do not need to be moved.
    Change the index “j”.
    j = j + 1 = 8

    Step 10.

    Compare the array element with index j with the pivot. 9 > 6. Array elements do not need to be moved.
    Change the index “j”.
    j = j + 1 = 9

    Step 11.

    Compare the array element with index j with the pivot. 8 > 6. Array elements do not need to be moved.
    Change the index “j”.
    j = j + 1 = 10

    Step 12.

    Compare the array element with index j with the pivot. 3 < 6. Swap the elements with indices i and j. Now the array looks like this
    [5, 4, 1, 2, 5, 10, 7, 7, 9, 8, 3, 6] –> [5, 4, 1, 2, 5, 3, 7, 7, 9, 8, 10, 6]
    Change the indexes
    i = i + 1 = 6
    j = j + 1 = 11

    Step 13.

    The “j” index is 11, which is the pivot index. We finish rearranging the elements in this iteration. Now we can split this array into 2 arrays. The left one will contain elements less than the pivot, and the right one is greater than or equal to the pivot. We leave the pivot in the middle between the arrays. It has already taken its place in the sorted array.
    The first element of the array in which all elements are greater than or equal to the pivot will be the element with index i. We transfer the pivot in the middle between the arrays.
    [5, 4, 1, 2, 5, 3] [6] [7, 7, 9, 8, 10]

    Then we sort the resulting 2 subarrays ([5, 4, 1, 2, 5, 3] and [7, 7, 9, 8, 10]) according to the above algorithm. We no longer use pivot “6”. Each subarray will have its own pivot

    To make it easier to write, I will describe the steps in the form of a table. You will be able to follow the steps and check the instructions above.

    Step 14-19.

    Sort the sub-array [5, 4, 1, 2, 5, 3]. pivot = 3; i = 0; j = 0

    CompareCurrent arrayProcedureResult arrayij
    5 > 3[5, 4, 1, 2, 5, 3]Do not swap elements.

    Increment “j”

    [5, 4, 1, 2, 5, 3]01
    4 > 3[5, 4, 1, 2, 5, 3]Do not swap elements.

    Increment “j”

    [5, 4, 1, 2, 5, 3] 02
    1 < 3[5, 4, 1, 2, 5, 3] Swap elements “i” and “j”.

    Increment “i” and “j”

    [1, 4, 5, 2, 5, 3]13
    2 < 3[1, 4, 5, 2, 5, 3]Swap elements “i” and “j”.

    Increment “i” and “j”

    [1, 2, 5, 4, 5, 3]24
    5 > 3[1, 2, 5, 4, 5, 3]Do not swap elements.

    Increment “j”

    [1, 2, 5, 4, 5, 3]25

    Step 20-24.

    Sort the sub-array [ 7, 7, 9, 8, 10]. pivot = 10; i = 0; j = 0

    CompareCurrent arrayProcedureResult arrayij
    7 > 10[7, 7, 9, 8, 10]Do not swap elements.

    Increment “j”

    [7, 7, 9, 8, 10]01
    7 > 10[7, 7, 9, 8, 10]Do not swap elements.

    Increment “j”

    [7, 7, 9, 8, 10]02
    9 > 10[7, 7, 9, 8, 10]Do not swap elements.

    Increment “j”

    [7, 7, 9, 8, 10]03
    8 > 10[7, 7, 9, 8, 10]Do not swap elements.

    Increment “j”

    [7, 7, 9, 8, 10]04

    We split the array. Now the general array looks like this:
    [1, 2] [3] [5, 4, 5] [6] [7, 7, 9, 8] [10]

    Then we sort the resulting 3 subarrays according to the above algorithm. It turned out 3 subarrays because in the second subarray ([7, 7, 9, 8, 10]) the pivot was the largest element in the subarray

    Step 25.

    Sort the sub-array [1, 2]. pivot = 2, i = 0, j = 0,

    CompareCurrent arrayProcedureResult arrayij
    1 < 2[1, 2]Swap elements “i” and “j”.

    Increment “i” and “j”

    [1, 2]01

    We split the array. Now the general array looks like this:
    [1] [2] [3] [5, 4, 5] [6] [7, 7, 9, 8] [10]

    Step 26-27.

    Sort the sub-array [5, 4, 5]. Pivot = 5, i = 0, j = 0,

    CompareCurrent arrayProcedureResult arrayij
    5 = 5[5, 4, 5]Do not swap elements.

    Increment “j”

    [5, 4, 5]01
    4 < 5[5, 4, 5]Swap elements “i” and “j”.

    Increment “i” and “j”

    [4, 5, 5]11

    Step 27-29.

    Sort the sub-array [7, 7, 9, 8]. pivot = 8, i = 0, j = 0,

    CompareCurrent arrayProcedureResult arrayij
    7 < 8[7, 7, 9, 8]Swap elements “i” and “j”.

    Increment “i” and “j”

    [7, 7, 9, 8]11
    7 < 8[7, 7, 9, 8]Swap elements “i” and “j”.

    Increment “i” and “j”

    [7, 7, 9, 8]22
    9 > 8[7, 7, 9, 8]Do not swap elements.

    Increment “j”

    [7, 7, 9, 8]23

    We split the array. Now the general array looks like this:
    [1] [2] [3] [4, 5] [5] [6] [7, 7] [8] [9] [10]

    Step 30.

    Sort the sub-array [4, 5]. pivot = 5, i = 0, j = 0,

    CompareCurrent arrayProcedureResult arrayij
    4 < 5[4, 5] Swap elements “i” and “j”.

    Increment “i” and “j”

    [4, 5] 11

    We split the subarray. Now the general array looks like this:
    [1] [2] [3] [4] [5] [5] [6] [7, 7] [8] [9] [10]

    Step 31.

    Sort the sub-array [7, 7]. pivot = 7, i = 0, j = 0,

    CompareCurrent arrayProcedureResult arrayij
    7 = 7[7, 7]Swap elements “i” and “j”.

    Increment “i” and “j”

    [7, 7] 11

    We split the subarray. Now the general array looks like this:
    [1] [2] [3] [4] [5] [5] [6] [7] [7] [8] [9] [10]
    The array sorting is finished.

    PlantUML diagram of the algorithm

    PlantUML Syntax:<br /> @startuml</p><p>start</p><p>partition “quickSort(minArrayIndex, maxArrayIndex)” {<br /> :set Pivot as last element;<br /> :set smallestElementIndex = minArrayIndex – 1;<br /> :set currentElementIndex = minArrayIndex;</p><p> repeat<br /> if (item at index currentElementIndex less or equal to Pivot) then (yes)<br /> :smallestElementIndex++;<br /> :swapElementsWithIndexes(currentElementIndex, smallestElementIndex);<br /> endif<br /> :currentElementIndex++;<br /> repeat while (currentElementIndex == pivot index) is (no)</p><p> :partitionElementIndex = smallestElementIndex+1;<br /> :swapElementsInArray(partitionElementIndex, pivotIndex);<br /> }</p><p>:quickSort(minArrayIndex, partitionElementIndex-1);<br /> :quickSort(partitionElementIndex+1, maxArrayIndex);</p><p>stop</p><p>@enduml<br /> ” usemap=”#plantuml_map”></p><h3 class=Sample code

    Below you will get link to github repo with Kotlin, Java, and Python code

    Download it from github
  • Insertion Sort Algorithm

    Insertion Sort Algorithm

    Insertion Sort appeared a long time ago. Intuitively, we use it to sort the cards in hand during card games. This is the easiest way to illustrate how this algorithm works.

    How the algorithm works

    Each element of the input sequence is scanned one at a time and compared with each element starting from the beginning of the list. The selected item takes its place in the list as soon as its place is found. And so with each element of the list.

    The time complexity of the algorithm is O(n^2), but on small amounts of data, the algorithm sometimes performs very well.

    Video shows how algorithm works

    Sequence of operations

    For example, let’s take the list [5, 3, 1, 6, 4].

    We take the first item from the list. This is “5”. If it were a list of one element, then we would say that a list of one element is always sorted.

    Moving on to the next item. This is “3”. Where should be “3” relative to “5”. Answer: before “5”. To do this, we must put “3” in front of “5”, and move “5”.

    Now the list has taken the following form [3, 5, 1, 6, 4]. We can now say that the sublist [3, 5] is sorted.

    Take the next item. This is “1”. Compare with the elements in front of it.
    5 > 1, 3 > 1.
    Obviously, “1” must come before “5” and “3”.

    Let’s move the sublist [3, 5] forward and put “1” in front of the sublist.

    Now the list has taken the following form [1, 3, 5, 6, 4]. We can now say that the sublist [1, 3, 5] is sorted.

    Take the next item. This is “6”. Compare with the elements in front of it.
    5 <6.
    It makes no sense to check further since the sublist [1, 3, 5] was sorted. Item “6” remains in place.

    Now the list has taken the following form [1, 3, 5, 6, 4]. We can now say that the sublist [1, 3, 5, 6] is sorted.

    Take the next item. This is “4”. Compare with the elements in front of it.
    6 > 4, 5 > 4, 3 < 4.
    There is no point in checking further since the sublist [1, 3, 5, 6] has been sorted. Obviously, “4” must come before “6”, “5”, but before “3”.

    Let’s move the sublist [5, 6] forward, and put “4” in front of the sublist.

    Now the list has taken the following form [1, 3, 4, 5, 6]. We have reached the end of the list and we can say that the list is all sorted from the original list.

    Diagram

    PlantUML Syntax:<br /> @startuml</p><p>start</p><p>while (End of array?) is (no)<br /> :Save Active Index;<br /> while (Previous element bigger than next element?) is (yes)<br /> :Swap elements;<br /> endwhile (no)<br /> endwhile (yes)<br /> :Finish. Array Sorted;</p><p>stop</p><p>@enduml<br /> ” usemap=”#plantuml_map”></p><h2 class=Sample code

    Below you will get a link to GitHub repo with Kotlin, Java, and Python source code

    Download it from github